[轉] 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);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM