ObjectContext with Entity Framework 6 inserting duplicates on existing related entities
Asked Answered
J

1

0

I'm creating this to hopefully save a few people some wasted hours, or in my case a Saturday.

The problem was as follows:

My main entity was called case in this instance and upon passing validation, I would save to the object context, like so

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

The issue was that a case had a related incident. I was adding a context aware item called incident, that I was looking up through context like so

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

As the code ran, I could see that model.Incident had an EntityKey and had state of Added and duplicates were being added. Not only that, the concluding reference after save was to the newly created record.

I thought that I immediately knew the answer, I simply needed to run the incident model through Attach beforehand like so

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

Wrong. Although it had EntityState of unchanged, it still entered a duplicate. Except this time, the resulting reference was the original Incident, and no longer the duplicate.

Johiah answered 15/11, 2015 at 0:1 Comment(0)
J
0

The solution was to cast into and override ObjectContext altogether with a DBContext like so

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

Despite the fact that the Incident entity had an EntityState of unchanged, ObjectContext still recognised it as new. DBContext seems much more state aware.

I hope this helps someone.

Johiah answered 15/11, 2015 at 0:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.