There is always a need to keep track of changes in the production database. We may want to create a log or maintain a history of these changes. There are multiple ways of doing this. One way is to have triggers on a table that creates these records along with who made the change and when was it made.

I was going to implement this with Entity Framework. I came across this good post about it. It starts with DDL to create an audit table, then the entity, and how to make use of the change tracker. The DbEntityEntry in the change tracker gives us the old and the new value of an entity. It shows how to do the logging by overriding the SaveChanges method on the DbContext.

If you are using the repository pattern, it won’t work as it is. When you add or attach an entity, the changes get detected. As a result, in the GetAuditRecordsForChange method, the original state and the current state of an entity will be the same and it will not create any logs. The details of how detect changes in EF works can be found here.

In order to resolve this, we need to delay the changes to be detected until the save method is called. The way to do this is by turning off the AutoDetectChangesEnabled to false before a method that triggers the detect changes. Here’s how it looks like :

 public virtual void Add(T entity)
 {
    DataContext.Configuration.AutoDetectChangesEnabled = false;
    DbSet.Add(entity);
 }

Now everything works fine and logs are properly created.