Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 6, Transaction Scope, Context and SaveChanges

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?
}
like image 214
Dee Avatar asked Aug 26 '26 00:08

Dee


1 Answers

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.

like image 64
tne Avatar answered Aug 29 '26 14:08

tne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!