Entity Framework Auditing

ef-auditIn a project I’m currently working on we wanted to log who changed what on particular data in our database. This will open up a lot of possibilities like proving who made a certain change, show your most recent changes and enable you to rollback changes to a previous point in time. There are off-course multiple options to solving this problem. We are using Entity framework and the DbContext has this ChangeTracker. We can use this in the SaveChanges method to nicely add this logic in a single place.

I first added an interface to mark a model to be audited as shown below.

You might not want to audit every property on a model. Therefor I added an attribute which can be used to exclude a property from being audited:

A model using both the interface and the attribute could is shown below:

Next, we need a model to save our audit logs and add this as a DbSet to our context. This could be a model like this one:

The last step is to implement the actual logic in the SaveChanges method in your context right before we save our changes. This following implementation searches for entries that implement the IAuditable interface. We will loop over all the properties of the entries that have been changed filtering out those that are marked with the DoNotAudit attribute.

 

 

You may also like...

Geef een reactie

Het e-mailadres wordt niet gepubliceerd. Verplichte velden zijn gemarkeerd met *

De volgende HTML-tags en -attributen zijn toegestaan: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">