Audit Trail in Entity Framework

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.
        }
    }
}
Advertisements

1 thought on “Audit Trail in Entity Framework”

Leave a Reply to Hashan Cancel reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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