Monday, October 13, 2008

Automatic Timestamping for Entity Framework

I was looking for a way to get ADO.NET Entity Framework to do magic timestamping à la Ruby on Rails ActiveRecord. I couldn't find any built in mechanism to accomplish this. Here's what I came up with:


public partial class MyEntityContext
{
partial void OnContextCreated()
{
SavingChanges += OnSavingChanges;
}

private void OnSavingChanges(object sender, EventArgs e)
{
var now = DateTime.Now;
foreach (var entry in ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified))
{
if (!entry.IsRelationship)
{
var timestampedEntity = entry.Entity as ITimestampedEntity;
if (timestampedEntity != null)
{
timestampedEntity.DateModified = now;
var entity = entry.Entity as EntityObject;
if (entity != null && entity.EntityState == EntityState.Added)
{
timestampedEntity.DateCreated = now;
}
}
}
}
}
}

internal interface ITimestampedEntity
{
DateTime DateCreated { get; set; }
DateTime DateModified { get; set; }
}


Now for every entity that implements the ITimestampedEntity interface, the DateCreated and DateModified fields will automagically be set/updated.

The above code is covered under the Logos Code Blog License.

No comments: