Program code:
[HttpPost] Public actionresult Edit (person person) { if (modelstate.isvalid) { = db. People.where (p = = P.id = Person . ID). FirstOrDefault (); // TODO Db. Entry (person). state = entitystate.modified; Db. SaveChanges (); return Redirecttoaction ("Index"); } return View (person);}
The above code attempts to remove the old data (Oldperson) for file deletion before updating the person to the database, the result page error:
Reference content
An object with the same key already exists in the Objectstatemanager. Objectstatemanager cannot track multiple objects with the same key.
If you do not take the old data, the code execution can execute normally, after some testing, the reason is that when reading the old data, the object will be added to the db when the "DB" is executed. Entry (person), an attempt was made to add person to the DB, but the person is the same as the key value of the previously added object, thus giving an error, which also explains why the old data is not being taken in error.
There are three solutions available below:
Person Oldperson = db. People.where (p = = P.id = Person . ID). FirstOrDefault (); // TODO Oldperson. Picurl = person . Picurl; Db. SaveChanges ();
Person Oldperson = db. People. asnotracking (). Where (p = p.id = = Person . ID). FirstOrDefault (); // TODOdb. Entry (person). state = entitystate.modified;db. SaveChanges ();
Person Oldperson = db. People.where (p = = P.id = Person . ID). FirstOrDefault (); // TODO db. Entry (Oldperson). Currentvalues.setvalues (person); Db. SaveChanges ();
Resources
[1]. An object with the same key already exists in the Objectstatemanager. The Objectstatemanager cannot track multiple objects with the same key
ASP. NET MVC3 Update error: An object with the same key already exists in Objectstatemanager