[英]TransactionScope transaction = new TransactionScope() VS TransactionScope s = context.Connection.BeginTransaction()
[英]Open new database connection in scope of TransactionScope without enlisting in the transaction
是否可以在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();
}
}
}
終於自己找到了:
另一個SqlConnection必須使用“ Enlist = false”進行初始化,這樣該連接將不會在同一事務中被登記:
using (var db = new SqlConnection(constring + ";Enlist=false")) {
...
另外,您的SaveErrorToDB
方法可以建立連接:
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.