"An object with the same key already exists in the ObjectStateManager," says the error message.

concurrency entity-framework objectstatemanager

Question

The entity I'm attempting to connect to the object context. The following InvalidOperationException is generated when I do that:

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

The item does not exist, according to my check in the object state manager:

//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 consider this fictitious illustration and let me know 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

Also welcome are responses in VB.

1
20
8/17/2010 2:50:38 PM

Accepted Answer

Your Contact entity could have two offspring that share the same EntityKey. Is it feasible, for instance, to use the same key to access two Address entities from the Contact entity?

A context will gladly provide a detached object graph with entities having the same key if you specify MergeOptions.NoTracking. A System.InvalidOperationException will be thrown if you attach the same object graph, however.

You should verify whether there are any objects with duplicate keys in the complete object graph that you are associating to the context, in my opinion.

7
8/10/2009 7:50:56 PM

Popular Answer

Answer: If you apply a navigation attribute to a tracked object, a new entity is created automatically. I didn't say that this was the issue since I didn't realize it was.

Dim s = context.States.FirstOrDefault()
Dim a As New Address
a.State = s

Dim state = a.EntityState '= Added

Since I was unaware of this, I kept wondering why the entity was being followed. I would remove the whole question, but because there are attempts at other answers that could be useful, I will keep it up. If you believe the question should be closed, please vote to do so.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow