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);


Sat Oct 23 2010 18:09:56 GMT-0700 (Pacific Daylight Time)


Next page: Map Reduce with MongoDB and NORM - a complete example

Previous page: Finding good, short domain names