Auditing linq to SQL entity classes

There are many ways to implement auditing on your entity classes. If you are not exposing linq to SQL entities to the presentation layer and prefer to use linq as a data access layer, than you can applying auditing on the linq entities in your business layer. The reason is, you have more control over the persistence and business layer is responsible for retrieving linq entities as well as saving them. However if you have considered that you can get away with using linq entities in your presentation layer because it provides partial classes where you can implement custom business logic than linq to SQL provides various easy ways to implement auditing features.

If you open up your linq to SQL designer generated code file, you will notice that for every entity there are three partial methods that gets called. For instance if you have a Category class, than the designer generated code will have 3 partial methods. CategoryInserted, CategoryUpdated and CategoryDeleted. Each of these partial methods has a parameter that exposes the entity that is about to be persisted. To implement auditing features, you can use this method and set the createdate and createdby properties on the entity and explicitly Insert the object in the database. Below is a sample code that demonstrate this usage.

image

Notice in the above code that I had to declare InsertCategory and UpdateCategory inside the NorthWindDataContext partial class instead of the Category class. Both InsertCategory and UpdateCategory are partial methods declared in the designer generated code for the DataContext. It would be nice if those partial methods were declared at the class level which would allow cleaner implementation of code instead polluting our custom DataContext class. Both partial methods get called just before the linq to SQL is persisting the Category class. It is important to understand that once you specify and implementation of Insert and Update partial methods, it is your responsibility to save those objects. You might be wondering just for putting some auditing, it would be cumbersome to actually be responsible for saving the objects. Well, if you look in my code above I am setting Createdate, CreatedByDate and than I am calling ExeucteDynamicInsert which takes care of inserting my category to the database. The concept is pretty same for UpdateCategory partial method where I am setting values for modifieddate and modifiedby properties and than calling ExecuteDynamicUpdate to send my updates to the database.

No Comments