How to check if Dotnet transaction is rolled back?

2019-04-10 11:14发布

How Can I check if a dotnet transaction is closed or not ?

3条回答
狗以群分
2楼-- · 2019-04-10 11:53

Your title asks one thing and your question asks another. so, I am going with your title.

If you want to know if the transaction is rolled back or set to rollback only, you can check

transaction.WasRolledBack // true if transaction is rolled back

Here, transaction is an instance of ITransaction

Edit (based on your comment):

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;
    }
  }
}

Now, you can check the isRolledBack flag to see if the transaction is rolled back

查看更多
对你真心纯属浪费
3楼-- · 2019-04-10 12:03

If you are on SQL server, you can use DBCC OPENTRAN

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

查看更多
三岁会撩人
4楼-- · 2019-04-10 12:04
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)
    {

    }
}
查看更多
登录 后发表回答