Unable to attach multiple entities for insertion (

2019-07-29 14:17发布

问题:

I have an entity that contains a list of other entities. The list of entities contains a primary key (identity), foreign key and a string. When I try to attach the parent entity, I get the exception An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

For some reason the Entity Framework (EF) thinks that this is a duplicate record. The records do have the same foreign key, but property that is the primary key (Id of type int) is set to 0 which, from my understanding, is acceptable since the column is an identity column.

Does anyone know what I'm doing wrong here?

回答1:

The same primary key values are not allowed if you attach the objects to the context. It's only possible if you add them to the context.

If you want to insert children for an already existing parent, you can try the following (example for EF >= 4.1):

// put parent and all children into Added state
context.Parents.Add(parent);

// reset state for parent to Unchanged, but not for the children
context.Entry(parent).State = EntityState.Unchanged;

context.SaveChanges();

I am assuming that parent and all children were detached from the context before this code snippet.

Edit

With ObjectContext:

// put parent and all children into Added state
objectContext.Parents.AddObject(parent);

// reset state for parent to Unchanged, but not for the children
objectContext.ObjectStateManager.ChangeObjectState(parent,EntityState.Unchanged);

objectContext.SaveChanges();