相关疑难解决方法(0)

使用MVC和实体框架实现审核日志/更改历史记录

我正在使用实体框架在更改历史/审核日志中构建我的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 …

c# asp.net-mvc audit entity-framework

31
推荐指数
2
解决办法
4万
查看次数

标签 统计

asp.net-mvc ×1

audit ×1

c# ×1

entity-framework ×1