Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

.NET Audit Implementation via the Entity Framework Change Tracker

Sign upSign InSign upSign InMatt BentleyFollowLevel Up Coding--ListenShareA guide to using the Entity Framework Change Tracker to audit data changes in .NET.Popularity for EF has skyrocketed since the release of Entity Framework Core and it has become one of the most widely used tools in the .NET ecosystem. This has largely been driven by a movement towards ‘code first’ database development (rather than ‘database first’). Gone are the days where we litter our solutions with untested and badly managed database scripts. For problems such as auditing, which historically relied on database triggers, this often finds us looking for new solutions. Luckily the Entity Framework ‘Change Tracker’ is here to help!Code for the implementation can be found here:github.comThe ChangeTracker class within Entity Framework is the magic sauce behind the scenes which works out exactly what has changed in our application. The various different EF providers simply translate the changes supplied by the ChangeTracker into a format that the database being used understands. This translation happens every time we execute SaveChanges on our DbContext.Luckily we can also access the ChangeTracker to understand what data has changed and apply those changes to our Audit tables (collections, containers, filestores, lakes, farms..?!). By abstracting the audit away alongside EF it doesn’t really matter what data store we are using, that’s one of the reasons we’re using EF in the first place!We can hook into the SaveChanges method in our DbContext and add any changes to our Audit right before:Here we have a clean solution with no nasty base classes that we need to apply to any of our Entity or DbContext classes. We are favouring composition over inheritance - Uncle Bob will be happy! This is in-fact the only real change that we need to make to our code.Every time data is changed via our DbContext and saved, we will add the changes to our audit. The format that the audit is stored in will differ depending on what type of database you are using — here is an example of how this looks if using SQL Server:For Inserts a JSON representation of the entity is stored. For Updates only the properties that have changed and their values are stored. The ChangeTracker is able to understand which parts of our entities have changed.All of the work is done by the AuditTracker which is injected into our DbContext. The AuditTracker is added to our DI container with a Scoped lifetime so that it matches the DbContext’s life. The AuditTracker’s job is fairly simple, it just takes the changes (Added, Modified or Deleted) from the ChangeTracker and applies them to the Audit in the DbContext. Any configuration options for the audit are held within the AuditOptions class. A simplified version of the AuditTracker is shown below:All that’s left is registering our AuditTracker in the DI container and configuring any AuditOptions that we’d like our AuditTracker to use. As with most programming problems, it is normally best to start with how we would like this to look for our consumers and then work out how to implement after. I like the Fluent approach for configuration which most modern libraries such as EF use, here is where I ended up:The interface above allows for entities to be opted-in to auditing without having to apply any interfaces or base classes to our entities. Each entity type can also be customised to control which properties and actions are audited. This type of interface is really easy to add to and extend in the future if we needed to incorporate new features.The configuration approach above can be implemented using a combination of extension methods and builder classes:The builder classes allow us to fluently configure our AuditOptions class before it is added to the DI container. A simplified version of these builder classes is shown below:What we end up with is a ‘code first’ solution for database auditing using Entity Framework. As the solution is fully contained within code right next to our application code, it is really easy to test! One of the many benefits to using EF is that this can be applied to any type of database which supports EF Core without having to change any code at all.The implementation within this article is fairly simple however the fluent framework provided makes it super easy to incorporate more complex use-cases in the future.A full version of the code can be found on my GitHub here.----Level Up CodingI’m a Software Architect who loves learning about new technologies and software development practices to take products to the next levelMatt BentleyinLevel Up Coding--8Sanjay PriyadarshiinLevel Up Coding--10Prathamesh GadekarinLevel Up Coding--4Matt BentleyinBetter Programming--4Anıl Dursun ŞENELinadessoTurkey--ImranJavaid--2Jatin Dave--Kerim Kara--1Crafting Code--Abdul Sammad--HelpStatusWritersBlogCareersPrivacyTermsAboutText to speechTeams



This post first appeared on VedVyas Articles, please read the originial post: here

Share the post

.NET Audit Implementation via the Entity Framework Change Tracker

×

Subscribe to Vedvyas Articles

Get updates delivered right to your inbox!

Thank you for your subscription

×