Entity Framework 6, Transaction Scope, Context and SaveChanges

entity-framework entity-framework-6 savechanges transactionscope

Question

Question pertains to transaction scope and context.SaveChanges(). If I'm processing a million records with a foreach, and I save after every, let's say, 1000 records by calling context.SaveChanges() inside a transaction scope and something fails after 10 000 have been processed and SaveChanges() called, will already saved data be rolled back? example:

using(TransactionScope ts = new TransactionScope( TransactionScopeOption.RequiresNew, new TimeSpan(0, 10, 0)))
{
    int counter = 0;
    using (MyEntities context = new MyEntities())
    { 
        foreach(var item in context.Items)
        {
            //process item
            if(counter >= 1000)
            {
                context.SaveChanges(); //if fail here, will already saved changes be rolled back?
                counter = 0
            }
        }
        context.SaveChanges();
    }
    ts.Complete();//what about here?
}
1
2
8/16/2015 5:18:09 PM

Popular Answer

The transaction scope takes precedence as long as the DbContext is enrolled in it, which it is by default.

Thus, if you don't call TransactionScope.Complete (e.g. because a DbContext-related exception throws you outside of the using block), everything will be rolled back as you expect. I encourage you to simply try it (best with a profiler on the side to monitor what's going on exactly).

In short, every SaveChanges will hit the database, but won't commit.

3
8/16/2015 4:16:42 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow