Error: Twitter did not respond. Please wait a few minutes and refresh this page.
- 11,977 hits
cultivate passion for everything else that goes on around programming
Tracking changes in Entity Framework 3.5 is pretty straight forward. I used the techniques described here: Audit Trail Using EF Part 1
Everything was fine except that the code in this article did not track changes to EntityReferences. So given an object A that has a reference to object B, the Entity Framework does not mark the reference from A to B as changed. Instead, when the reference changes, it deletes the previous reference and adds the new reference as an ObjectStateEntry. This way, when calling ObjectStateManager.GetObjectStateEntries(), there will be 2 objects returned, one with the EntityState.Deleted state and one with the EntityState.Added state. Additionally, the ObjectStateEntry.GetModifiedProperties() method does not return any information about the change of the reference.
So I adapted the code from the article to retrieve the changed reference values too. The following code shows how I did that, based on the code from the original article.
The interesting part begins at line 39, where I try to find all relationships, added or deleted, that are related to the given entry. By finding the deleted references we are able to set the original value of the EntityKey. If no deleted reference is found, we try to find an added relation. If an added relation exists, but no deleted one, than we can assume that the reference was not set before the change, so we set it’s EntityKey to null.
Thus we can store our OldData and our NewData into the audit trail database.