Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramework, TransactionScope and SaveChange

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

like image 660
Neb Avatar asked Jan 06 '23 13:01

Neb


1 Answers

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."

like image 118
Ashley Kurkowski Avatar answered Jan 09 '23 01:01

Ashley Kurkowski