EF Core Audit Trail

Entities changes audit

A few months back I was interviewing for a full stack position and the hiring company CTO asked me to work on a little exercise: “Build an Audit Trail for Entities Changes”.  The purpose of such exercise was to create an automatic system that would log entities changes in the database. After completing the exercise I thought sharing it could help someone else in need of such tool and me to remember it. So here it is, check my Github repo.

Using .NET Core and EntityFramework Core 1.0.0 (this was done a few months back with v. 1.0.0 now there are already newer versions) I created a little console app to seed the DB, randomly change the records and list the log.

The way I solved this problem was inspired by a Julie Lerman Pluralsight course (can’t remember which one) and a nice post by Matthew P Jones, it seems that overriding the SaveChanges method of the DbContex is probably the best way to go.  In Julie course she has all her entities inherit from an interface that expose Id, DateModified, DateCreated and User and she automatically log this information within the entityobject.  By overriding the SaveChanges method we have access to all the properties that are being affected along with the OriginalValue and NewValues so we can log each property change accordingly (see AuditContext class).