在TransactionScope范围内打开新的数据库连接,而不在事务中登记

时间:2013-08-10 10:27:55

标签: c# transactionscope

是否可以在TransactionScope中打开新的SqlConnection,而无需引用事务中的其他连接?在内部事务中,我需要运行另一个不应该参与事务的命令。

void test() {
    using (var t = new TransactionScope())
    using (var c = new SqlConnection(constring))
    {
        c.Open();
        try 
        {
             using (var s = new SqlCommand("Update table SET column1 = 1");
             {
                   s.ExecuteScalar();  // If this fails
             }
             t.Complete();
        }
        catch (Exception ex)
        {
             SaveErrorToDB(ex);  // I don't want to run this in the same transaction
        }
    }
}

// I don't want this to get involved in the transaction, because it would generate
// a Distributed transaction, which I don't want. I Just want the error to go to the
// db not caring about it is run inside the TransactionScope of the previous function.
void SaveErrorToDB(Exception ex) {
    using (var db = new SqlConnection(constring)) {
          db.Open();

          using (var cmd = new SqlCommand("INSERT INTO ErrorLog (msg) VALUES (" + ex.Message + "))
          {
                cmd.ExecuteNonQuery();
          }
    }

}

2 个答案:

答案 0 :(得分:3)

终于找到了自己:

必须使用“Enlist = false”初始化其他SqlConnection,然后才会在同一事务中登记该连接:

using (var db = new SqlConnection(constring + ";Enlist=false")) {
...

答案 1 :(得分:0)

或者,您的if (!cart) { cart = []; } 方法可以建立连接:

SaveErrorToDB