The ObjectStateManager already has an object with the same key. Multiple objects with the same key cannot be tracked by the ObjectStateManager.

asp.net-mvc-3 entity-framework

Question

I have following code to add or update the Entity object. finding the object by primary key, based on the response I am adding or updating the object.

Adding record works, but during update its giving this error message "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key"

In my MSSQL database I have only one record.

var v = db.Envelopes.Find(model.ReportDate, model.Service);
if (v == null)
{
    db.Envelopes.Add(model);
    db.SaveChanges();
    ViewBag.status = "Record Add successfully";
    ModelState.Clear();
}
else
{
    db.Entry(model).State = EntityState.Modified;
    db.SaveChanges();
}

How can I fix this error message?

1
52
9/7/2012 5:49:05 PM

Accepted Answer

As mentioned by @anon you can't attach model once you loaded the entity with the same key. The changes must be applied to attached entity. Instead of this:

db.Entry(model).State = EntityState.Modified;

use this:

db.Entry(v).CurrentValues.SetValues(model);
88
4/15/2011 7:40:17 AM

Popular Answer

If an earlier query read the entity to be updated and that's why you're getting the error, you can change that query to AsNoTracking. See the AsNoTracking example in: http://www.asp.net/entity-framework/tutorials/advanced-entity-framework-scenarios-for-an-mvc-web-application



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow