Data committed even though System.Transactions.TransactionScope.Commit() not called

前端 未结 4 1737
温柔的废话
温柔的废话 2020-12-19 12:39

Under what circumstances can code wrapped in a System.Transactions.TransactionScope still commit, even though an exception was thrown and the outermost scope ne

4条回答
  •  伪装坚强ぢ
    2020-12-19 13:18

    Be aware how TransactionScope works:
    It sets property System.Transactions.Transaction.Current at the begining of using scope and then set it back to previous value at end of using scope.

    Previous value depends on where given scope is declared. It can be inside another scope.


    You can modify code like this:

    using (var sqlConnection = new ConnectionScope())
    using (var transaction = new TransactionScope())
    {
        sqlConnection.EnlistTransaction(System.Transactions.Transaction.Current);
        // Do something that modifies data
        transaction.Complete();
    }
    

    I show this possibility for those who have their code more complicated and cannot simply change code to open DB connection first.

提交回复
热议问题