Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 724
Shimmy Weitzhandler Avatar asked Jul 15 '09 14:07

Shimmy Weitzhandler


2 Answers

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.

like image 156
Daniel Richardson Avatar answered Oct 03 '22 16:10

Daniel Richardson


Answer is (and I didn't mention that this was the problem, since I didn't know it is), that if you set a navigation property to a tracked entity the new entity is automatically added:

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

Dim state = a.EntityState '= Added

Since I didn't know that I kept on wondering how come the entity is tracked. I would delete the entire quesion but since there is effort of other answer that might be helpful I will leave it here, vote to close if you think it should be closed.

like image 34
Shimmy Weitzhandler Avatar answered Oct 03 '22 14:10

Shimmy Weitzhandler