ObjectContext with Entity Framework 6 by inserting duplicates into existing related objects

I am creating this in order to hope to save a few wasted people, or in my case on Saturday.

The problem was this:

My main essence was called case in this instance, and after passing the test I would save it in the context of the object, for example

context.AddToCases(caseModel); context.SaveChanges(); 

The problem was that an incident occurred in the event of an incident. I added a context sensitive element called an incident, which I looked through such a context

 caseModel.Incident = context.Incidents.SingleOrDefault(i => i.IncidentNumber == jumpIncidentNumber); 

As the code worked, I could see this model. Incident had EntityKey and the state of Added and Duplicates was added. Not only that, the final link after saving was associated with the newly created record.

I thought that I immediately understood the answer, I just needed to run the incident model through Attach in advance so

 context.Attach(incident); caseModel.Incident = incident; 

Wrong. Despite the fact that EntityState has not changed, it still introduced a duplicate. With the exception of this time, the resulting link was the original incident, not a duplicate.

0
c # asp.net-mvc entity-framework
Nov 15 '15 at 0:01
source share
1 answer

The solution was to completely or partially overlap the ObjectContext with the DBC text in this way

 if (model.Incident != null) { DbContext dbContext = new DbContext(context, true); dbContext.Entry(model.Incident).State = EntityState.Unchanged; } 

Although the incident object had the EntityState unchanged, the ObjectContext still recognized it as new. DBContext seems much more state aware.

I hope this helps someone.

0
Nov 15 '15 at 0:01
source share



All Articles