Search code examples
c#.netentity-frameworkentity-framework-4entity-framework-4.1

EF Code First: Where can I find the SavingChanges Event?


OK, this may be a newbie question, but how/where can I subscribe to the ObjectContext.SavingChanges event as mentioned for example in this post.

I've only two relevant classes in my demo app: The "Country" class and a class which holds the EF Code First "definitions":

internal class TestDb : DbContext
{
    public DbSet<Country> Countries { get; set; }       
}

Any hint is highly appreciated.


Solution

  • You should be able to do this:

    internal class TestDb : DbContext  
    {  
        public void SetSavingChanges(EventHandler evt) 
        {
                var oc = this as IObjectContextAdapter;
                oc.ObjectContext.SavingChanges -= evt;
                oc.ObjectContext.SavingChanges += evt;
        }
    
        public DbSet<Country> Countries { get; set; }  
    }