[转] EF cannot be tracked because another instance of this type with the same key is already being tracked

本文转自:http://stackoverflow.com/questions/6033638/an-object-with-the-same-key-already-exists-in-the-objectstatemanager-the-object

 

cannot be tracked because another instance of this type with the same key is already being tracked

 

 

If you load the entity from the context you cannot attach an entity with the same key again.

The first entity is still kept in internal context cache and context can hold only one instance with given key value per type (it is called identity map and I described it here in other situation).

You can solve it by detaching former instance but you don't have to. If you only need to save new values you can use this:

  • ObjectContext API: context.YourEntitySet.ApplyCurrentValues(newEntity);
  • DbContext API: context.Entry(oldEntity).CurrentValues.SetValues(newEntity);

 

posted on 2017-02-23 09:57  freeliver54  阅读(3715)  评论(0编辑  收藏  举报

导航