Open new database connection in scope of TransactionScope without enlisting in the transaction

StackOverflow https://stackoverflow.com/questions/18160991

  •  24-06-2022
  •  | 
  •  

Question

is it possible to open a new SqlConnection inside TransactionScope, without referencing the other connection in the transaction? Inside transaction, I need to run another command which should not take part in the transaction.

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();
          }
    }

}
Was it helpful?

Solution

Found it myself finally:

The other SqlConnection must be initialized with "Enlist=false", then the connection will not be enlisted in the same transaction:

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

OTHER TIPS

Alternatively your SaveErrorToDB method could take a connection:

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, c);  // I don't want to run this in the same transaction
        }
    }
}

void SaveErrorToDB(Exception ex, SqlConnection c) {
      using (var cmd = new SqlCommand("INSERT INTO ErrorLog (msg) VALUES (" + ex.Message + ", c))
      {
            cmd.ExecuteNonQuery();
      }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top