ObjectContext with Entity Framework 6 inserting duplicates on existing related entities

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.


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.

链接地址: http://www.djcxy.com/p/33544.html

上一篇: 什么是Unchanged状态实体键值

下一篇: ObjectContext与实体框架6在现有相关实体上插入重复项