获取对Entity Framework中对象的所有更改 [英] Getting all changes made to an object in the Entity Framework

查看:148
本文介绍了获取对Entity Framework中对象的所有更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在保存所有更改之前,是否有一种方法可以在Entity Framework中获取对对象所做的所有更改。原因是我想在我们的客户数据库中创建一个日志表:

Is there a way to get all the changes made to a object in the Entity Framework before it saves all changes. The reason for this is that i want to create a log table in our clients database:

so ...

有没有办法在保存更改之前获取当前数据库值(旧)和新值(当前)?

Is there a way to get the current database values(old) and the new values(current) before changes are saved?

如果没有,我该如何实现以一般的方式,所以我所有的View Models都可以继承?(我使用MVVM + M结构)

If not, how can i achieve this in a generic way, so all my View Models can inherit from this?(I am using the MVVM + M Structure)

推荐答案

您可以使用ObjectContext的 ObjectStateManager,GetObjectStateEntry 获取对象的 ObjectStateEntry ,它在 OriginalValues 和 CurrentValues 属性。您可以使用 GetModifiedProperties 方法。

You can use ObjectContext's ObjectStateManager,GetObjectStateEntry to get an object's ObjectStateEntry, which holds its original and current values in the OriginalValues and CurrentValues properties. You can get the names of the properties that changed using the GetModifiedProperties method.

您可以写如下:

var myObjectState=myContext.ObjectStateManager.GetObjectStateEntry(myObject);
var modifiedProperties=myObjectState.GetModifiedProperties();
foreach(var propName in modifiedProperties)
{
    Console.WriteLine("Property {0} changed from {1} to {2}", 
         propName,
         myObjectState.OriginalValues[propName],
         myObjectState.CurrentValues[propName]);
}

这篇关于获取对Entity Framework中对象的所有更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆