Drew Noakes
Drew Noakes

Reputation: 310907

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.

Upvotes: 5

Views: 4412

Answers (2)

Jens H
Jens H

Reputation: 4632

In addition to Ladislav Mrnka's suggestion: Not really generic, but at least a possible solution: Code Generation and T4 Text Templates. This allows you to add your own custom logic to each entity when the models are generated.

In your case, you could implement the needed traversing functionality to check the navigation properties.

Upvotes: 1

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

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.

Upvotes: 10

Related Questions