Archive for November, 2011

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.

Enity Framework: Unable To Delete Entity Because Primary End Of Foreign Key Constraint Has Been Deleted

November 23, 2011

I got this error even though the Foreign Key constraint had been deleted from the database and I had re-executed all my EF Template files, had refreshed my Model from the database and had deleted the relevant Navigation propertry from my Model.

Thing is , I had forgotten to physically delete the Association in the Model Designer .edmx file. When I did that and then re-ran my Model Template file all was well.

So I reckon I had only refreshed the secondary (referencing) table in the FK side. Next time I will refresh the primary (referenced) table as well.

That’s all. Get back to what you were doing. The door is the wooden thing in the wall behind you.