0
votes

Im geting exception

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

I have entity that is detached and also has key in ObjectStateManager, this is what I dont understand. How is this posible?

What Im trying to do is to atach entity back to context when it comes back from client (Asp MVC controller).

If I do this

db.MyEntity.Attach(myEntity);

I get the first exception.

I know that it is detached because when I try to call

db.MyEntity.Context.LoadProperty(myEntity, e => e.myProperty);

I get excetion that my entity is detached (which it should be, why is the key in ObjectStateManager?).

So to sum it up I think I have entity that has key in ObjectStateManager and is detached. How do I attach it? Em I missing something? Or em I misunderstanding something?

Thank you for any suggestions.

Edit: As @Ladislav Mrnka corectly stated my problem is that Im loading the entity with same id in one request processing. Im doing this because I want original values of the entity for comparing and if there are problems I want to display it back to user, but I need to attach it which is problem because there is entity with old values still present in ObjectStateManager. Im attaching this entity because I also need to display lazy Loaded properties. What is the right aproach to do this? Just to make new query for entity?

1
Do you create new context for each request processing? Do you call Attach only once? Did you load entity with the same id in the same request processing? - Ladislav Mrnka
I create new context per request. I attach only once BUT you are right, Im loading entity with same id in the same request!!! (that could be the problem!) - Eduard

1 Answers

2
votes

You can't have loaded entity and attach entity with same Id. You must either detach the loaded one or merge changes into loaded one (also check ApplyCurrentValues method).