Holly Styles Holly Styles - 3 months ago 16
ASP.NET (C#) Question

LINQ to SQL Basic insert throws: Attach or Add not new entity related exception

I am trying to insert a record. This code worked but has stopped working I don't know why. Here is the code:

using (SAASDataContext dc = new SAASDataContext())
tblAssessment a2 = new tblAssessment();

a2.AssessmentCentreId = centreId;
a2.AttemptNumber = 1;


CurrentAssessmentId = a2.AssessmentId;

The code compiles but throws the exception below on the

Exception thrown:

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

is a foreign key on
, centreId is a valid existing centre id,
AssessmentCentreId and AttemptNumber are the only not null fields all other columns allow nulls.

I have googled but all the results seem to pertain to people trying to attach entities pulled from other disconnected DataContext's I'm not doing that so I'm stumped.



dc.DeferredLoadingEnabled = false;

at the top of the using block makes it work, but I'd like to know why coz I have no idea at the moment sufficiently advanced technology being indistinguishable from magic right now :)


The issue is that the Centre object doesn't exist in the context. It's in the db, but not "in your hand" with a2. Try this:

a2.AssessmentCentre = dc.AssessmentCentres.SingleOrDefault(

The AssessmentCentre object will then exist in the context, which means there will be no problem with attaching it to a2.