Entity Framework 4.1 and OriginalValues/CurrentValues and DbContext

橙三吉。 提交于 2020-01-16 15:22:31

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/7002987/entity-framework-4-1-and-originalvalues-currentvalues-and-dbcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!