Posts Tagged ‘Fun With Zeppelins’

Adding existing entity to Association: An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

November 24, 2011

I got this error when adding a new entry to a Property in my Entity which is a Navigation property.

To get around this you must Detach the entity already in your Context which has the same key as the entity you are trying to add to your Context. The Gotcha is that if you insert an entity into a List which is a Navigation Property then Entity Framework marks that entity as ‘Added’ even though it is not actually New.

As my now dearly beloved Stack Overflow contact, Shimmy, explained

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

In my case, adding a Zeppelin to a Hanger which contains a list of Zeppelins:

SelectedHanger.Zeppelins.Add(zep); // Throws ‘object with same key…’ exception

The exception is thrown because my ctx.Zeppelins already contained a Zeppelin with Id equal to zep.Id. Same object key, therefore KABOOM. That zep BTW, was not an actual new Zeppelin but a Zeppelin selected from a list of Zeppelins in a DropDown. Even though Selectedhanger.Zeppelins did not contain a Zeppelin with Id = zep.Id, the fact that I had added zep to SelectedHanger.Zeppelin caused EF to initialise the EntityState of zep to ‘Added’ in the Context. Capiche ?

So to successfully add zep to Hanger.Zeppelins:

Zeppelin ctxZep = ctx.Zeppelins.Where(z => z.Id == zep.Id).Single();
ctx.Zeppelins.Detach(ctxZep);
ctx.Zeppelins.Attach(zep);

Noice.

Advertisements