Auditing with Entity Framework

Dheeraj Kumar Gunti

Reading Time : ( words)

Tracking of changes to the data can be handled in Entity framework using Self Tracking Entities. This can be identfied by using ObjectStateManager class which has complete information of the entities and their state (Added, Modified, Deleted). We can track the changes using this ObjectStateManager. Following is the example for recording the changes. Create a schema in the Database for Audit as below:

Create an application add an entity model to your application and include all your objects to the entity model. Once the model (EDMX) is created right click on the entity designer and choose Add Code Generation Item, It opens a dialog where you can choose the Code Generation strategies. Default code generation type is EntityObjectDesigner. Select Self Tracking Entities as your code generation item. It Creates two files in your solution. Model.tt, Model.Context.tt (These are called as T4 (Template Text Transformation) templates) Do Handling changes to the object Model.Context.cs file which has Initialize() method, where you need to write your handler to track changes. In Entity Framework Context.SaveChanges will be used to apply data in database. So we will create a handler for Saving Changes in Model.Context.cs so that at the time of applying data to DB changes will be captured and stored in our Audit Table.

Here we are creating an event handler named SaveJournalChanges which tracks the entity changes. We are making a new partial class with the same name as entity class. In that we are changing the save changes functionality to accomplish Audit Process.

ObjectContext.DetectChanges detects the changes in context object.

From UI you can call Context.SaveChanges which inturn calls SaveJournalChanges method.



Sample