EF Code First DbContext.SavingChanges

Unfortunately there is no SavingChanges event on the code first DbContext, but there is a way to get to it.

The DbContext used for data access with Entity Framework Code First has a simplified API compared to the ObjectContext which is good. Unfortunately it is a bit too simple sometimes. For example there is no built in event that can be used to act before pending changes are written to the database. Fortunately, there is a way to get to the underlying ObjectContext which has such an event.

[TestMethod]
public void TestSavingChanges()
{
    using (var ctx = new CarsContext())
    {
        var objCtx = ((IObjectContextAdapter)ctx).ObjectContext;

        bool eventCalled = false;

        objCtx.SavingChanges += (sender, args) => eventCalled = true;

        ctx.SaveChanges();

        Assert.IsTrue(eventCalled);
    }
}

Of course it would be really simple to create an own event inside an override of SaveChanges but having a built in one is even more simple. There is also a ObjectMaterialized event that is fired each time an object is loaded from the database as well as some additional methods and properties that are not available directly on the DbContext.

Software Development is a Job – Coding is a Passion

I'm Anders Abel, a systems architect and developer working for Kentor in Stockholm, Sweden.

profile for Anders Abel at Stack Overflow, Q&A for professional and enthusiast programmers

The complete code for all posts is available on GitHub.

Popular Posts

Archives

Series

Powered by WordPress with the Passion for Coding theme.