.Net Core 2.1中的主要交易发生错误时,我该如何回滚子交易

时间:2018-10-27 04:12:24

标签: c# .net .net-core .net-framework-version sqltransaction

我在项目(.Net Core 2.1)中使用了两个不同的数据库。 如果主要交易发生错误,我将无法回滚子交易。

以下是步骤:

  1. 使用DB1的事务打开新连接
  2. 对DB1的患者表执行更新操作(成功)
  3. 打开与DB2事务的新连接
  4. 对患者表执行DB2的更新操作(成功)
  5. 为DB2提交事务并关闭连接
  6. 对DB1患者表执行更新操作(发生错误)
  7. DB1的回滚事务
  8. 如何回滚DB2事务?

下面是我的代码段。

public class CheckTransations
{
    public void CheckTran()
    {
        string strConnString1 = @"data source = 177.16.8.68\sqlexpress; initial catalog = DB1; persist security info = True; user id = sa; password = 99$indd; MultipleActiveResultSets = True; ";
        string strConnString2 = @"data source = 177.16.8.68\sqlexpress; initial catalog = DB2; persist security info = True; user id = sa; password = 99$indd; MultipleActiveResultSets = True; ";
        SqlTransaction objTrans1 = null;
        SqlTransaction objTrans2 = null;
        using (SqlConnection objConn1 = new SqlConnection(strConnString1))
        {
            objConn1.Open();
            objTrans1 = objConn1.BeginTransaction();
            SqlCommand objCmd1 = new SqlCommand("update Patient set chartNumber = 'C5' where PatientId = 5", objConn1, objTrans1);
            try
            {
                var PatientId = objCmd1.ExecuteNonQuery();
                using (SqlConnection objConn2 = new SqlConnection(strConnString2))
                {
                    objConn2.Open();
                    try
                    {
                        objTrans2 = objConn2.BeginTransaction();
                        SqlCommand objCmd2 = new SqlCommand("update Patient set ChartNumber = 'C029' where PatientId = 29", objConn2, objTrans2);
                        var PatientId2 = objCmd2.ExecuteNonQuery();
                        objTrans2.Commit();
                    }
                    catch (Exception ex)
                    {
                        objTrans2.Rollback();
                        throw;
                    }
                    finally
                    {
                        objConn2.Close();
                    }
                }
                objCmd1 = new SqlCommand("update Patient set chartNumber = 'C5' where PatietId = 1036", objConn1, objTrans1);
                var PatientId1 = objCmd1.ExecuteNonQuery();
                objTrans1.Commit();
            }
            catch (Exception ex)
            {
                objTrans1.Rollback();
            }
            finally
            {
                objConn1.Close();
            }
        }
    }
}

0 个答案:

没有答案