交易范围不适用于.net中的多项操作

时间:2019-01-29 12:26:27

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

我在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));
            }
        }

1 个答案:

答案 0 :(得分: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();
    }
  }
}