【问题标题】:Transactionscope rollback事务范围回滚
【发布时间】:2014-06-27 01:09:40
【问题描述】:

我在主要方法中有一个方法。如果父方法失败,我需要子方法能够回滚。这两个数据连接使用不同的服务器。在我添加事务范围之前,它们运行良好。但是当我将它们绑在一起时,子方法会中止。

编辑:错误消息:分布式事务管理器 (MSDTC) 的网络访问已被禁用。请使用组件服务管理工具在 MSDTC 的安全配置中启用 DTC 进行网络访问。

public static void LoopStudent() 
{
  try 
  {
    using(TransactionScope scope = new TransactionScope()) 
    {
      String connString = ConfigurationManager.AppSettings["DBConnection"];
      using(SqlConnection webConn = new SqlConnection(connString)) 
      {
        webConn.Open();
        String sql = "select * from students";
        using(SqlCommand webComm = new SqlCommand(sql, webConn)) 
        {
          using(SqlDataReader webReader = webComm.ExecuteReader()) 
          {

            if (webReader.HasRows) 
            {
              while (webReader.Read()) 
              {
                int i = GetNextId();
              }
            } 
            else 
              Console.WriteLine("wrong");
          }
        }
      }

      scope.Complete();
    }
  }
  catch (Exception ex) 
  {
    Console.WriteLine("Error " + ex.Message);
  }

} //End LoopThroughCart         

public static int GetNextId(String str) 
{
  int nextId = 0;
  String connString = ConfigurationManager.AppSettings["SecondDBConnection"];
  try 
  {
    using(TransactionScope scope = new TransactionScope()) 
    {
      using(SqlConnection webConn = new SqlConnection(connString)) 
      {
        webConn.Open();
        using(SqlCommand webComm = new SqlCommand("GetNextId", webConn)) 
        {
          //do things
        }
      }
      scope.Complete();
    }
  } 
  catch (TransactionAbortedException ex) 
  {
    Console.WriteLine("TransactionAbortedException Message: {0}", ex.Message);
  } 
  catch (ApplicationException ex) 
  {
    Console.WriteLine("ApplicationException Message: {0}", ex.Message);
  }
  return nextId;
} //End GetNextId

【问题讨论】:

    标签: c# transactions transactionscope


    【解决方案1】:

    如果你的inner方法中没有使用RequireNew,那么如果父事务提交失败,inner方法会自动回滚。

    你遇到了什么错误?

    【讨论】:

    • 我在问题中添加了错误消息。我认为您所说的仅适用于相同的连接?我正在连接两台服务器。
    • 转到“运行”并输入“msdtc”。现在,导航到“组件服务 -> 计算机 -> 我的电脑 > 分布式事务协调器”,然后右键单击“本地 DTC”并选择“属性”。打开“安全”选项卡。在那里您可以看到 DTC 选项,甚至是“网络”选项。如果这有帮助,请不要忘记将其标记为帮助他人的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-14
    • 2015-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    相关资源
    最近更新 更多