ASP. NET MVC3 Update error: An object with the same key already exists in Objectstatemanager

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.