Unable to attach a detached entity: "An object with the same key already exists in the ObjectStateManager"

Shimmy Weitzhandler picture Shimmy Weitzhandler · Jul 15, 2009 · Viewed 20.8k times · Source

I am trying to attach an entity to the ObjectContext. When I do so, the following InvalidOperationException is thrown:

An object with the same key already exists in the ObjectStateManager.
The ObjectStateManager cannot track multiple objects with the same key.

I checked in the object state manager and the item does not exist:

//Data context is actually the object context.
ObjectStateEntry contact;
while ( //Should only work once since it should be true if the item was attached
          !DataContext.ObjectStateManager.
          TryGetObjectStateEntry(Contact, out contact)
      )
      DataContext.Attach(Contact); //Here is the exception thrown.

Or look at this abstract example and tell me if it makes sense:

EntityState state = Contact.EntityState; //Detached

DataContext.Attach(Contact); //Throws the exception.
DataContext.AttachTo("Entities.Contacts", Contact); //Throws the Exception

var detached = DataContext.ObjectStateManager.
                   GetObjectStateEntries(EntityState.Detached);
//InvalidArgumentException - detached entities cannot be in the obj state mgr

Answers in VB are welcomed too.

Answer

Daniel Richardson picture Daniel Richardson · Aug 10, 2009

Could your Contact entity have two child entities with the same EntityKey? For example, is it possible to get from the Contact entity to two Address entities with the same key?

If you specify MergeOptions.NoTracking a context will happily return a detached object graph that contains entities with the same key. However, when you attach the same object graph a System.InvalidOperationException will be thrown.

I would suggest that you look at the entire object graph that you are attaching to the context and check if there are objects with duplicate keys in it.