问题
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