Sunday, August 18, 2013

Entity Framework: An object with the same key already exists in the ObjectStateManager

I attempted to obtain the current values of a database row to compare them with a value that I was setting using the Entity Framework. When all was set, I tried to update the database with the modified object using the following:
db.Entry(objNew).State = System.Data.EntityState.Modified;
...and that was when the Entity Framework threw an exception with the message:
An object with the same key already exists in the ObjectStateManager

The problem is that when I fetched an existing value, the object state manager had one object so when I tried to set the state of the other object to modified, it noticed that an object with the same key already exists. There are two ways to deal with this problem.

Solution 1: Update the existing object

This is a pretty straightforward solution. Instead of setting the state of the new object to modified, I change the state of the old object, but instead of setting each property manually, it can be done like this:
db.Entry(objOld).CurrentValues.SetValues(objNew);
followed by a db.SaveChanges() call.
.
Solution 2: Detach the old object

To detach an object, you simply have to set the state to Detached, just as you would when you want to set the state of the new object to Modified. Here's how it is done:
db.Entry(objOld).State = System.Data.EntityState.Detached;
You can then update the database with the new object, as you would do normally.

No comments: