2

トランザクション内の他の接続を参照せずに、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();
          }
    }

}
4

2 に答える 2

3

最終的に自分で見つけました:

他の SqlConnection は「Enlist=false」で初期化する必要があります。その後、接続は同じトランザクションに登録されません。

using (var db = new SqlConnection(constring + ";Enlist=false")) {
...
于 2013-08-10T16:39:28.060 に答える