Search code examples
c#asp.net-mvctransactionscope

TransactionScope check if transaction commited ok


Hello is there a way to check if a transaction using TransactionScope was committed or rolledback?


Solution

  • The actual Commit is not happening until the TransactionScope is disposed. If the Commit fails for any reason an exception will be thrown. You should Catch that exception and put your logic for failed transaction in the Catch block. If no exception has been thrown you should be assured that Commit was successful. If for any reasons that I cant think of, you don't trust the framework, you can always create another Scope and query the results to make sure they have been applied.

    var transactionFailed = false;
    try
    {
        using (var tx = new TransactionScope())
        {
            tx.Complete();
        }
    }
    catch (TransactionAbortedException ex)
    {
        transactionFailed = true;
        writer.WriteLine("TransactionAbortedException Message: {0}", ex.Message);
    
    }
    catch (ApplicationException ex)
    {
        transactionFailed = true;
        writer.WriteLine("ApplicationException Message: {0}", ex.Message);
    }
    catch (Exception ex)
    {
        transactionFailed = true;
        writer.WriteLine("Exception Message: {0}", ex.Message);
    }