开发者

Entity Framework 4.1 and OriginalValues/CurrentValues and DbContext

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 开发者_C百科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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜