我正在使用实体框架在更改历史/审核日志中构建我的MVC应用程序.
因此,在编辑方法中public ActionResult Edit(ViewModel vm),我们找到了我们正在尝试更新的对象,然后使用TryUpdateModel(object)将表单中的值转置到我们尝试更新的对象上.
我想在该对象的任何字段更改时记录更改.所以基本上我需要的是在编辑对象之前复制一个对象,然后在TryUpdateModel(object)完成它的工作之后对它进行比较.即
[HttpPost]
public ActionResult Edit(ViewModel vm)
{
//Need to take the copy here
var object = EntityFramework.Object.Single(x=>x.ID = vm.ID);
if (ModelState.IsValid)
{
//Form the un edited view model
var uneditedVM = BuildViewModel(vm.ID); //this line seems to confuse the EntityFramework (BuildViewModel() is used to build the model when originally displaying the form)
//Compare with old view model
WriteChanges(uneditedVM, vm);
...
TryUpdateModel(object);
}
...
}
Run Code Online (Sandbox Code Playgroud)
但问题是当代码检索"未编辑的虚拟机"时,这会导致EntityFramework中的一些意外更改 - 因此TryUpdateModel(object);抛出一个UpdateException …