Jamie Kurtz

Promoting architectural simplicty

  Home  |   Contact  |   Syndication    |   Login
  21 Posts | 0 Stories | 26 Comments | 5 Trackbacks

News



Archives

Monday, February 25, 2008 #

I've been looking quite a bit at the new ADO.NET Entity Framework. I'm really hoping to be able to implement the technology to replace our data access layer with all of its generated database and .NET code.

One of the first things I found myself trying to figure out was updating a DateLastMaint field whenever a change is persisted by the ObjectContext. Our applications use this field religiously, and its update needs to be baked down into the architecture so the application developers don't need to mess with it.

In addition to updating fields on entities, we also need to be support auditing. I'm not sure if this little trick would solve that problem, but it's a start. So here's how I did...

I created a ModelFactory class that serves up EDM models that are pre-hooked to update this DateLastMaint field upon saving. Here's the code for the class:

public static class ModelFactory
{
    public static T CreateModel<T>() where T: ObjectContext
    {
        T model = Activator.CreateInstance<T>();
        model.SavingChanges += new EventHandler(model_SavingChanges);
        return model;
    }

    static void model_SavingChanges(object sender, EventArgs e)
    {
        ObjectContext context = (ObjectContext)sender;

        IEnumerable<ObjectStateEntry> changes = context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified);

        foreach (ObjectStateEntry entry in changes)
        {
            DateTime dateLastMaint = DateTime.Now;
            int ordinal = entry.CurrentValues.GetOrdinal("DateLastMaint"); 
            entry.CurrentValues.SetDateTime(ordinal, dateLastMaint);
        }
    }
}

Then to use the ModelFactory class, just do the following:

MyEntities context = ModelFactory.CreateModel<MyEntities>()

One thing to work out yet: The ObjectContext / model should be instantiated within a using block. But doing so caused the underlying connection to get disposed, so my little test app couldn't persist the changes back to the database. Not sure yet how to recreate an instance of the model and have existing changes merged with it???