How to check if Dotnet transaction is rolled back?

半世苍凉 提交于 2019-12-06 06:21:12

问题


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


回答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:


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:


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

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



来源:https://stackoverflow.com/questions/4456301/how-to-check-if-dotnet-transaction-is-rolled-back

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!