Search code examples
.netentity-frameworkentity-framework-4

Detect which properties changed on an Entity Framework EntityObject


I want to read changes within an EntityObject for inclusion in a report.

For example:

Name: Before After

Location: Before After

Is there a generic way to do this? I'm using EF4 with default entity class generation (not POCO).

These entities will be attached, so they should be being tracked for changes. I cannot see a means to do this via the IEntityWithChangeTracker interface.

Traversing navigation properties would be nice, but it'd be enough of a win to just report upon changed primitive properties.


Solution

  • You can retrieve ObjectStateEntry for your entity and check contents of CurrentValues and OriginalValues. Try this (untested):

    ObjectStateEntry entry = objectContext.ObjectStateManager.GetObjectStateEntry(entity);
    foreach (string property in entry.GetModifiedProperties()) {
        object oldValue = entry.OriginalValues[property];
        object newValue = entry.CurrentValues[property];
    }
    

    This will not handle navigation properties and I'm not sure how it would work with complex types.