【问题标题】:Transaction Scope not working for multiple operations in .net事务范围不适用于 .net 中的多个操作
【发布时间】:2019-01-29 12:26:26
【问题描述】:

我在 DoWork() 方法中有多个操作,我正在使用事务范围,但它没有按预期工作。

当 DataInsert2() 出现故障时,它应该恢复 DataInsert1() 和 DataInsert2()。但目前它只恢复 DataInsert2()..?

如果我在这里犯了任何错误,请告诉我。

//DoWork()

public void DoWork()
            {
                try
                {

                  TransactionOptions tranOptions = UtilityBL.GetTransOptions();
                    using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, tranOptions))
                    {
                        if (DataInsert1())
                        {
                          DataInsert2() ;
                        }
                        scope.Complete();
                    }
                }
                catch (Exception ex)
                {
                    log.Info(string.Format(UploadMessages.FailedMsg));
                   if (ContextUtil.IsInTransaction)
                        ContextUtil.SetAbort();
                }
          }

//DataInsert1

public bool DataInsert1()
        {
           bool fileUploadStatus=false;
           try
            {

                DAL.InsertDetails1() 
                fileUploadStatus=true;

            }
            catch (Exception ex)
            {
                log.Info(string.Format(UploadMessages.FailedMsg));
           }
            return fileUploadStatus;
        }

//DataInsert2

public bool DataInsert2()
        {
           try
            { 
                DAL.InsertDetails2() 
            }
            catch (Exception ex)
            {
                log.Info(string.Format(UploadMessages.FailedMsg));
            }
        }

【问题讨论】:

  • 在不知道DAL 中的内容的情况下,无法判断为什么这可能不起作用。特别是,TransactionScope 本身并没有真正做任何事情,在其中运行的代码必须是事务感知的并选择加入。如果(例如)它跨越新线程来工作,或者如果你的工作“ re doing 实际上并不支持事务。
  • 看起来您依赖于在DoWork() 中捕获的异常来回滚您的事务,但在数据插入方法中您正在吞噬它们。
  • @ChrisPickford 我也尝试在数据插入捕获块中添加事务 abort()。但仍然是同样的问题。
  • stackoverflow.com/questions/494550/… 您不需要显式回滚,因此您甚至可以将您的 try-catch 块放在事务范围之外。它开箱即用,您只需要 Complete()。

标签: c# sql asp.net .net transactions


【解决方案1】:

您应该能够按如下方式简化您的代码。您的DataInsert 方法正在吞噬DAL.InsertDetails 方法抛出的任何异常。

public void DoWork()
{
  TransactionOptions tranOptions = UtilityBL.GetTransOptions();
  using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, tranOptions))
  {
    try {
      DAL.InsertDetails1();
      DAL.InsertDetails2();
      scope.Complete();
    }
    catch (Exception ex)
    {
        log.Info(string.Format(UploadMessages.FailedMsg));

        if (ContextUtil.IsInTransaction)
          ContextUtil.SetAbort();
    }
  }
}

【讨论】:

  • 让我试试这个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-29
  • 2017-07-12
  • 1970-01-01
  • 1970-01-01
  • 2021-08-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多