实体框架4.1和OriginalValues / CurrentValues和DbContext [英] Entity Framework 4.1 and OriginalValues/CurrentValues and DbContext

查看:183
本文介绍了实体框架4.1和OriginalValues / CurrentValues和DbContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用DbContext与Ef 4.1,我正在尝试审核我的一些实体的所有更改。我可以捕获实体的任何属性的原始值和当前值,但是我无法弄清楚如何捕获NavigationProperty的关联(Foreign Key)OriginalValues。有没有人想过这个?

解决方案

您必须将外键包含在您的实体中,以便他们被跟踪为正常值必须将您的 DbContext 转换为 ObjectContext 并使用更强大(更麻烦) ObjectStateManager 其中可以为实体和关系获取 ObjectStateEntry 的实例。



DbContext 转换为 ObjectContext 使用: p>

  var objectContext =((IObjectContextAdapter)dbContext).ObjectContext; 

要获取条目使用:

  var entires = objectContext.ObjectStateManager 
.GetObjectStateEntries(〜EntityState.Unchanged);

通过条目迭代并使用他们的状态 CurrentValues OriginalValues 要进行日志记录的属性。关系不应该被修改,所以你只需要检查删除的和添加的关系(而不是更新旧的被删除和添加新的)。问题是删除一次,因为它们不会提供你的价值。您可以通过更改其状态,获取值并将状态更改为已删除来尝试小型解决方法 - 如果不起作用,则无法记录关联关系的旧值。


I'm currently using DbContext with Ef 4.1, and I'm trying to audit all changes some of my entities. I can capture the original and current values for any Properties of an entity, however I cannot figure out how to capture the association (Foreign Key) OriginalValues of a NavigationProperty. Has anyone figured this out?

解决方案

You must either include foreign keys to your entities so they will be tracked as normal values or you must convert your DbContext to ObjectContext and use more powerful (and more cumbersome) ObjectStateManager where you can get instances of ObjectStateEntry for both entities and relations.

To convert DbContext to ObjectContext use:

var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;

To get entries use:

var entires = objectContext.ObjectStateManager
                           .GetObjectStateEntries(~EntityState.Unchanged);

Iterate through entries and use their State, CurrentValues and OriginalValues properties to do your logging. Relationship should not be in modified so you should only need to check for deleted and added relationships (instead of updating the old is deleted and new is added). The problem is with deleted once because they will not provide you their values. You can try small workaround by changing their state, get values and changing state back to deleted - if it doesn't work you will not be able to log old values for relations.

这篇关于实体框架4.1和OriginalValues / CurrentValues和DbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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