EF6 using transaction in inner methods

73 Views Asked by At

I've been seen many posts about using ef6 transactions but all the SaveChanges() are in the same block.

What I want is to use a transaction and call multiple functions inside a block, each one having SaveChanges() but belonging to the main transaction block.

I already tried code like the following:

using(var transaction = context.Database.BeginTransaction())
{
    try
    {
        doSomething(); //Has SaveChanges() and also sub functions with also SaveChanges()

        doSomethingElse(); //Same as before
    }
    catch (Exception exp)
    {

        transaction.Rollback();
    }
    transaction.Commit();
}

What happens is that transaction.Rollback() does nothing at all.

I assume that the inner functions have their own transaction scope and don't care about this one. So how can I put this to work?

1

There are 1 best solutions below

1
Schellaine On

I did a quick check in LinqPad:

void Main()
{
    using (var transaction = Database.BeginTransaction())
    {
        var z = z_pdd_log.First(p => p.id == 100001);
        Console.WriteLine(z.result);
        z.result = "TEST";
        this.SaveChanges();
        Console.WriteLine(z.result);
        transaction.Rollback();
        DetachAll();
        z = z_pdd_log.First(p => p.id == 100001);
        Console.WriteLine(z.result);
    }
}

public void DetachAll()
{
    foreach (DbEntityEntry dbEntityEntry in ChangeTracker.Entries())
    {
        if (dbEntityEntry.Entity != null)
        {
            dbEntityEntry.State = System.Data.Entity.EntityState.Detached;
        }
    }
}

which results in:

OK
TEST
OK

The rollback works.

Maybe your doSomthing-Methods did not throw an exception so the rollback never happened. Could you please check?