Exception: An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
With the Entity Framework 4 it's relatively easy to get this exception but it can be hard to figure out why it's happening and how to fix it.
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
One of the causes of this problem is a complex entity graph with multiple paths between two objects.
One simple trick that can work is to use the Foreign Key id values to establish new relationships instead of setting the actual Entity objects on a relation.
For example, instead of this
Mention statement = new Mention
{
DateTimeMentioned = dateTimeMentioned,
Collection = collection,
Item = item,
PhysicalEntity = thing
};
this.Mentions.AddObject(statement);
Do this ...
Mention statement = new Mention
{
DateTimeMentioned = dateTimeMentioned,
CollectionId = collection.Id,
ItemId = item.Id,
PhysicalEntityId = thing.Id
};
this.Mentions.AddObject(statement);