首页 > 解决方案 > 事务范围不适用于 .net 中的多个操作

问题描述

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

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

让我知道我是否在这里犯了任何错误。

//做工作()

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

//数据插入1

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

                DAL.InsertDetails1() 
                fileUploadStatus=true;

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

//数据插入2

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

标签: c#sqlasp.net.nettransactions

解决方案


您应该能够按如下方式简化代码。您的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();
    }
  }
}

推荐阅读