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 Reply

Your email address will not be published.

Please do only post comments to the contents here. If you need help on the topic described in this post, please post a question at Stack Overflow instead (if you want you can link back to this post in your question). There is a much higher chance that you will get help quickly on Stack Overflow than here.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>