EntityFramework 4 – Part Deux : Audit Info
In last post showed how easy it was to use POCO classes in EntityFramework v4, a feature called “All Code”. This new feature, facilitates creating domain models but how about other features you may already have using other ORMs like NHibernate? Let’s see how we can achieve automatic audit logging in EF v4.
I’m using the bits included in Visual Studio 2010 Beta 2 with additional features included in Entity Framework 4 CTP 2 (not included in VS 2010) which you can download here.
For running Linq queries, we probably already have an existing ObjectContext implementation (see previous post). The ObjectContext class provides. To create audit log, we need to tap into SavingChanges event and populate audit properties. Having an “EntityBase* class as layer super-type that contains Inserted, InsertedBy, Updated and UpdatedBy audit fields we can add this cross cutting concern, across all of our entities which is what I’ve done here, but obviously instead of using a base class, you can do this with an Interface. Let’s create an AuditableObjectContext which will do the auditing part when the entity is saved by either an Update or an Insert:
public class AuditableObjectContext : ObjectContext
Our existing SalesObjectContext class from previous post, now looks like this:
public class SalesObjectContext : AuditableObjectContext
It was pretty easy and painless to create auditing fields, don’t you think? In the next post, we’ll see how to implement repository pattern using POCO mode and EF v4.