When you are working with certain projects which involves the Customer records, you might need to track of each and every addition/change made to system along with who create, modify and delete the records.
Here I am going to show you how to implement the Audit Trail using Entity Framework in ASP.NET. Entity Framework keeps track of entity objects when we have modified them. Here I am going to use the ‘ObjectStateManager’ which is EF’s caching management object to access the entity states and their changes.
Firstly create the AuditLog table using below script, which stores the audit type (Insert/Update/Delete), DB table name, primary key, column name, old value, new value, action date and the UserId who make the change.
As EF creates the Entity Data Model in the form of partial class for your DB entities, follow the same approach by created the DB entities partial class by extending ObjectContext class.
In the next step, override the SaveChanges() method of the EF as shown below:
We will have one custom class to capture the changed entities from the EF as shown below:
Now we will write a method to access the entries which are eligible to log in the database table. Inside the method we will get the Added, Modified and Deleted entities from the ObjectStateManager. From each entity we will read the Original Values and Current Values, and store them to CustomLog class.
Here is the full length code of getting the list of changed entities in EF:
Finally make a call to the above method from the overloaded SaveChanges() method as shown below:
That’s all for now…! I hope you got the idea of doing the Audit Trail using the ObjectStateManager’ of ObjectContext. In my next post I will try to explain doing the same using DbContext.
Thanks a lot for reaching here and reading my article…..!