Audit Trail in Entity Framework

02 May

When saving changes (ObjectContext.SaveChanges())in Entity Framework, we have access to original and current values. These values can be used for audit trailing / change tracker.

The class DbContext.ChangeTracker provides access to these values. As one might have suspected, the entity context must derived from DbContext.

To access these values, we can loop through ChangeTracker.Entries<T>() or ChangeTracker.Entries(), which is a collection of DbEntityEntry<T>.

More over, DbEntityEntry<T>.Entity.State, type of EntityState, will tell us what operation is being performed (Added, Modified, or Deleted)

Then, to access original or current values, we dive into DbEntityEntry<T>.OriginalValues or DbEntityEntry<T>.CurrentValues, both of which are type of DbPropertyValues.

public override int SaveChanges()
    foreach (var entry in ChangeTracker.Entries<Product>())
        if (entry.State == EntityState.Added)
            // Do some actions.
        else if (entry.State == EntityState.Modified)
            // Do some actions.

            // Get current values.
            var currentId = entry.CurrentValues["Id"];
            var currentName = entry.CurrentValues["Name"];

            // Get original values.
            var originalId = entry.OriginalValues["Id"];
            var originalName = entry.OriginalValues["Name"];
        else if (entry.State == EntityState.Deleted)
            // Do some actions.
1 Comment

Posted by on May 2, 2012 in General


Tags: ,

One response to “Audit Trail in Entity Framework

  1. Hashan

    January 6, 2014 at 1:48 am

    savechanges cannot override… in objectcontext, savechanges method doesn’t have virtual keyword


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: