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.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.