在获取实体框架对象所做的所有更改 [英] Getting all changes made to an object in the Entity Framework

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

问题描述

有没有办法让在实体框架为对象进行它保存所有更改之前的所有更改。这样做的原因是,我希望在我们的客户数据库中创建日志表:

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:

所以...

有没有一种方法来获取当前数据库中的值(旧)和新值(当前)保存之前的变化?

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

如果不是,我怎么能在一个通用的方式做到这一点,所以我的所有视图模型可以从这个继承?(我使用的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中的<一个href=\"http://msdn.microsoft.com/en-us/library/bb155228.aspx\">ObjectStateManager,GetObjectStateEntry获取对象的<一href=\"http://msdn.microsoft.com/en-us/library/system.data.objects.objectstateentry.aspx\">ObjectStateEntry,其中持有其原有的和当前值在<一个href=\"http://msdn.microsoft.com/en-us/library/system.data.objects.objectstateentry.originalvalues.aspx\">OriginalValues和<一个href=\"http://msdn.microsoft.com/en-us/library/system.data.objects.objectstateentry.currentvalues.aspx\">CurrentValues属性。你可以使用<一个改变了的属性的名称href=\"http://msdn.microsoft.com/en-us/library/system.data.objects.objectstateentry.getmodifiedproperties.aspx\">GetModifiedProperties方法

You can use ObjectContext's ObjectStateManager,GetObjectStateEntry to get an object's ObjectStateEntry, which hold 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]);
}

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

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