gpt4 book ai didi

c# - 在不加入事务的情况下在 TransactionScope 范围内打开新的数据库连接

转载 作者:行者123 更新时间:2023-11-30 22:15:07 27 4
gpt4 key购买 nike

是否可以在 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")) {
...

关于c# - 在不加入事务的情况下在 TransactionScope 范围内打开新的数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18160991/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com