I am working on a c# project with EntityFramework and the last developer wrote that:
using (System.Transactions.TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted }))
{
try
{
//... do somehting
context.SaveChanges();
//... do some other work
context.SaveChanges();
scope.Complete();
}
catch (Exception ex)
{
context.RollbackChanges();
scope.Complete();
}
}
I don't understand why he is using TransactionScope
. I tried to throw an exception between the 2 SaveChanges
and it didnt rollback the first call modification.
Why using TransactionScope
?
Thanks
This should explain it for you - https://blogs.msdn.microsoft.com/alexj/2009/01/11/savechangesfalse/
Edit: as per szer's request.
They key take-away from the link is :
"If you call SaveChanges() or SaveChanges(true),the EF simply assumes that if its work completes okay, everything is okay, so it will discard the changes it has been tracking, and wait for new changes."
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