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

前端 未结 4 1734
温柔的废话
温柔的废话 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:01

    The answer turned out to be because I was creating the TransactionScope object after the SqlConnection object.

    I moved from this:

    using (new ConnectionScope())
    using (var transaction = new TransactionScope())
    {
        // Do something that modifies data
    
        transaction.Complete();
    }
    

    to this:

    using (var transaction = new TransactionScope())
    using (new ConnectionScope())
    {
        // Do something that modifies data
    
        transaction.Complete();
    }
    

    and now it works!

    So the moral of the story is to create your TransactionScope first.

提交回复
热议问题