我们可以在ASP.NET中的事务范围中调用两种双二词方法



你好,我是C#中事务范围的新手。我有两个插入查询,一个属于用户countcountcreation,其中存储了登录名,另一个是在员工表中将员工详细信息插入员工详细信息作为外键。

我编写了两种不同的方法来插入在用户量表表中,并插入用户量表后,将用户accountid伪造并插入员工表中。情况是当Useraccount创建成功并创建员工失败的时候,它必须回滚。因此,我想知道我们是否可以使用交易范围以及在这两个插入方法之间进行呼叫?如果发生错误,我们可以回滚这些范围中调用的方法。示例代码:

private void CreateEmp()
{
  using (TransactionScope scope = new TransactionScope())
  {
    try
    {
        CreateUserAccount();
        CreateEmployee();
        scope.Complete();
    } 
    catch (TransactionAbortedException ex)
        {
    }
  }
}

帮助您感谢!预先感谢!

您可以在事务范围中调用尽可能多的功能。如果您想要两种方法可以处理他们自己的连接(开放/使用/关闭/处置),但是它们会默默成为环境交易的一部分,而无需我们通过任何内容。

这应该回答您的问题。要快捷键,只需阅读代码示例中的评论

是。这就是为什么我们使用交易范围。

手头任务:当用户单击"更新"按钮时,我需要在4个表中插入一行。

以下内容对我有效:

我在类中添加了一个变量,其中4个更新方法是,如果以4种方法捕获的异常,则将其设置为false。在没有此事的情况下致电tran.Complete();对我不起作用。

/* This variable is used to check if updating the scorecard succeeded. 
Set this variable to false in catch blocks of the 4 update methods. */
private bool bAllUpdated = true;

我的更新单击方法看起来像:

/* Showing the try-catch block only */
try
{
    using (TransactionScope tran = new TransactionScope())
    {
         UpdateMethod1();
         UpdateMethod2();
         UpdateMethod3();
         UpdateMethod4();
         if (bAllUpdated == true)
         {
             tran.Complete();
             lblSC_Success.Visible = true;
         }
         else
             throw new TransactionAbortedException();
    }
}
catch (TransactionAbortedException ex)
{
      bAllUpdated = false;
      lblSCEditWarning.Text = "There was an error and your changes where NOT saved. " + ex.Message;
}
catch (ApplicationException ex)
{
    bAllUpdated = false;
    lblSCEditWarning.Text = "There was an error and your changes where NOT saved. " + ex.Message;
}
catch (Exception ex)
{
    bAllUpdated = false;
    lblSCEditWarning.Text = "There was an error and your changes where NOT saved. " + ex.Message;
}
finally
{
    // Clean up the temp tables
    // Refresh page
}

最新更新