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?
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With