本文介绍了使用相同连接的TransactionScope和方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用可以使一个包含多个事务性SQL语句的方法。现在,我需要调用也使用相同连接的第二种方法,并且在 connection.Open()
处收到以下异常:
I'm using TransactionScope
to make a method that contains multiple sql statements transactional. Now i need to call a second method that also uses the same connection and i receive following exception at connection.Open()
:
因此,这是伪代码:
public static void Method1()
{
using (TransactionScope scope = new TransactionScope())
{
bool success = true; // will be set to false in an omitted catch
using (var connection = new SqlConnection(ConnectionString1))
{
// ...
if(somethingHappened)
Method2();
}
if(success)
scope.Complete();
}
}
public static void Method2()
{
using (var connection = new SqlConnection(ConnectionString1))
{
connection.Open(); // BOOOM!
// ...
}
}
如何避免重复此代码而不重复 Method1
中 Method2
中的代码?
How to avoid this exception without repeating the code from Method2
in Method1
?
推荐答案
如果在同一 TransactionScope
下打开了多个连接,它将自动升级为DTC。
If more then one connection are open under same TransactionScope
it will be automatically escalated to the DTC.
您需要先关闭第一个连接,然后再调用 Method2
。
You need to close first connection before calling Method2
.
public static void Method1()
{
using (TransactionScope scope = new TransactionScope())
{
bool success = true; // will be set to false in an omitted catch
bool isSomethingHappened
using (var connection = new SqlConnection(ConnectionString1))
{
isSomethingHappened = // Execute query 1
}
if(somethingHappened)
Method2();
if(success)
scope.Complete();
}
}
这篇关于使用相同连接的TransactionScope和方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!