如何检查Dotnet事务是否回滚?

时间:2010-12-16 00:12:36

标签: c# commit rollback sqltransaction

如何检查dotnet交易是否已关闭?

3 个答案:

答案 0 :(得分:3)

你的标题问了一件事,你的问题又问了另一件事。所以,我想要你的头衔。

如果您想知道事务是否已回滚或仅设置为回滚,您可以检查

transaction.WasRolledBack // true if transaction is rolled back

此处,transaction是ITransaction的实例

修改(根据您的评论)

var isRolledBack = false;
using (var connection = new SqlConnection())
{
  using (var transaction = connection.BeginTransaction())
  {
    try
    {
      // do your stuff here with transaction
    }
    catch (Exception ex)
    {
      transaction.Rollback();
      isRolledBack = true;
      throw;
    }
  }
}

现在,您可以检查isRolledBack标志以查看事务是否已回退

答案 1 :(得分:1)

using(TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew)){

    try{
        //Do something;

        scope.Complete();  //denotes the transaction completed successful.
    }
    catch(TransactionAbortedException ex)
    {

        //scope.Complete(); is never called, the transaction rolls back automatically.
    }
    catch(ApplicationException ex)
    {

    }
}

答案 2 :(得分:0)

如果您在SQL服务器上,则可以使用DBCC OPENTRAN

http://msdn.microsoft.com/en-us/library/ms182792.aspx