实体框架4.1和OriginalValues / CurrentValues和DbContext [英] Entity Framework 4.1 and OriginalValues/CurrentValues and DbContext
问题描述
您必须将外键包含在您的实体中,以便他们被跟踪为正常值必须将您的 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屋!