有没有办法找到在 MVC 中的标准 'edit' 方法之后更改的字段的前值?
Is there a way to find the former value of a field changed after the standard 'edit' method within MVC?
首先是我正在尝试做的一些代码:
[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);
}
当我 运行 这段代码时,数据库说它无法保存,因为有另一个实体具有相同的主键。这是合乎逻辑的,因为我正在更改它时从数据库中选择它。但是,有没有办法获取该对象,以便我可以检查对象中声明的字段的先前值,以便我知道在编辑 '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.
List checkiffalseapproved = db.Persons.AsNoTracking().Where(y => y.ID == person.ID).AsQueryable().ToList();这样它就与原始数据库分离了,我仍然可以在不打扰 EF
的情况下获取信息
此代码修复了它
首先是我正在尝试做的一些代码:
[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);
}
当我 运行 这段代码时,数据库说它无法保存,因为有另一个实体具有相同的主键。这是合乎逻辑的,因为我正在更改它时从数据库中选择它。但是,有没有办法获取该对象,以便我可以检查对象中声明的字段的先前值,以便我知道在编辑 '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.
List checkiffalseapproved = db.Persons.AsNoTracking().Where(y => y.ID == person.ID).AsQueryable().ToList();这样它就与原始数据库分离了,我仍然可以在不打扰 EF
的情况下获取信息此代码修复了它