C# – LINQ TO SQL error: An attempt has been made to Attach or Add an entity that is not new

cdatacontextlinq-to-sql

"An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported."

I have scene a lot of solutions dealing with the Attach() method but I'm just trying to add in a new record. Not sure what is going on.

Here is my code, It is failing on the star'd line.:

try
            {
                LINQDataContext datacontext = new LINQDataContext();


                TrackableItem ti = datacontext.TrackableItems.FirstOrDefault(_t => _t.pkId == obj.fkTrackableItemId);
                arcTrackableItem ati = new arcTrackableItem();
                ati.barcode = ti.barcode;
                ati.dashNumber = ti.dashNumber;
                ati.dateDown = ti.dateDown;
                ati.dateUp = ti.dateUp;
                ati.fkItemStatusId = ti.fkItemStatusId;
                ati.fkItemTypeId = ti.fkItemTypeId;
                ati.partNumber = ti.partNumber;
                ati.serialNumber = ti.serialNumber;
                ati.archiveDate = DateTime.Now;

                datacontext.arcTrackableItems.InsertOnSubmit(ati);
                datacontext.SubmitChanges();


                arcPWR aItem = new arcPWR();
                aItem.comments = obj.comments;
                aItem.fkTrackableItemId = ati.pkId;
                aItem.fkPWRStatusId = obj.fkPWRStatusId;
                aItem.PwrStatus = obj.PwrStatus;


                **datacontext.arcPWRs.InsertOnSubmit(aItem);**
                datacontext.SubmitChanges();

Best Answer

Looks like obj was built using a different dataContext and that needs to be created using the same dataContext rather than instantiating a new one.

A quick solution might be to pass in a dataContext rather than instantiating a new one inside this method.