Saturday, September 28, 2013

Adding Log Feature to Entity Framework

Today I will show how you can add auditing / logging to entity framework. [Code First]

Please note that this is an old blog post. An update to date instruction page is now at https://github.com/bilal-fazlani/tracker-enabled-dbcontext/wiki & repository is shared on github



As developers who deal with database everyday, we all are aware of those 4 columns that are present at the end of all tables,  i.e. create date,update date,create user, update user, etc. Depending on implementation these columns may differ in different scenario. But the objective here is same, auditing/logging.

The same can be achieved with entity framework by adding 4 extra properties to all POCO classes. This can be made more efficient by inheriting from and a class who already has these properties. To be honest, I have never followed that approach with entity framework.


I follow a different approach where you have a separate table which is dedicated for log entries.

-------------------------------------------------------------------------
Update: 5 March 2015
  1. For ASP.NET MVC 5 and above use: TrackerEnabledDbContext.Identity
  2. For everything else use: TrackerEnabledDbContext
Update: 26 March 2015
If you find any bugs, please raise them on : github.com
-------------------------------------------------------------------------

How do we do it ? - In 4 easy steps

Step 1: Install the nuget package

Install the package I have created from nuget package. 
you can easily do that by typing "Install-Package TrackerEnabledDbContext" in the package manager console.

Package Manager Console

Step 2: Inherit

Inherit your DbContext from TrackerContext (or TrackerIdentityContext for MVC 5 or above). It's present in TrackerEnabledDbContext namespace.
And instantiate it with connection string for example :

        public DatabaseContext()
            : base("DefaultConnection")
        {
        }

Add a migration and update your database. You will notice that 2 new tables are created for recording changes. (dbo.AuditLog)

      

Step 3: Decide

Decide which tables you want to track. and apply [TrackChangesattribute to those POCO classes.
Once you do that all the columns in that table will be tracked. In case you want to skip tracking for some specific columns, you can apply [SkipTrackingattribute to those columns (properties).

here is an example :

    

Step 4: Start using

Whenever you make a change in database, you call DbContext.SaveChanges(). Now you have an overload available for that which takes an integer. This should be the logged in persons user id. Please note that if you don't pass the user id, this change will not be recorded into the tracking table.

Example :
    databaseContext.SaveChanges(userId);


Now with version 2.5, there new methods available to fetch logs from audit log table.

       var ProductLog = context.GetLogs<Product>(426);

Please leave your comments and feedbacks. Thank you.





No comments:

Post a Comment

Continuous Integration for .net Core projects ( for beginners )

Hello developers, This article is about how you can easily setup continuous integration for your dot net core (dnx) projects with appveyo...