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

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);

Leave a Comment