有没有办法找到标准'编辑后改变的字段的前值? MVC中的方法?

时间:2015-01-15 10:35:16

标签: asp.net-mvc entity-framework

首先是我尝试做的一些代码:

[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
public ActionResult Edit(Person person, HttpPostedFileBase filetoupload)
{
      if (ModelState.IsValid)
      {
            //db is the context and person is the object to be changed
            person.PeopleManagerApproved = false;
            Person x = db.Persons.Find(person.ID);
            //connection with the database to persist the changes.
            db.Entry(person).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("../Person/Details/" + person.ID);
       }
       return View(person);
 }

当我运行此代码时,数据库表示它无法保存,因为另一个实体具有相同的主键。这是合乎逻辑的,因为我在数据库中选择它,因为它被改变了。有没有办法,抓住那个对象,这样我就可以检查在对象中声明的字段的先前值,这样我就可以知道在编辑'之后,哪些值已经改变了。对象

错误信息是:

Attaching an entity of type 'Smoelenboek.Models.Person' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

1 个答案:

答案 0 :(得分:0)

列表checkiffalseapproved = db.Persons.AsNoTracking()。其中​​(y => y.ID == person.ID).AsQueryable()。ToList();这样它就脱离了原始数据库,我仍然可以在不打扰EF的情况下获取信息

此代码修复了它