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?
Share
You must either include foreign keys to your entities so they will be tracked as normal values or you must convert your
DbContexttoObjectContextand use more powerful (and more cumbersome)ObjectStateManagerwhere you can get instances ofObjectStateEntryfor both entities and relations.To convert
DbContexttoObjectContextuse:To get entries use:
Iterate through entries and use their
State,CurrentValuesandOriginalValuesproperties 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.