在我们的项目中,我们使用TransactionScope来确保我们的数据访问层在事务中执行它的操作.我们的目标是不要求在最终用户的计算机上启用MSDTC服务.
麻烦的是,在我们开发人员的一半机器上,我们可以在禁用MSDTC的情况下运行.另一半必须启用它或他们得到"MSDTC on [SERVER] is unavailable"错误消息.
它真的让我摸不着头脑,让我认真地考虑回归到基于ADO.NET事务对象的家庭式的类似TransactionScope的解决方案.这看起来很疯狂 - 在我们开发人员的一半上工作(并且没有升级)的代码确实在其他开发人员上升级.
我希望得到一个更好的答案,跟踪为什么交易升级到DTC但不幸的是它没有.
这是一个会导致问题的示例代码,在尝试升级的机器上,它会尝试在第二个连接上升级.Open()(是的,当时没有其他连接打开.)
using (TransactionScope transactionScope = new TransactionScope() {
using (SqlConnection connection = new SqlConnection(_ConStr)) {
using (SqlCommand command = connection.CreateCommand()) {
// prep the command
connection.Open();
using (SqlDataReader reader = command.ExecuteReader()) {
// use the reader
connection.Close();
}
}
}
// Do other stuff here that may or may not involve enlisting
// in the ambient transaction
using (SqlConnection connection = new …Run Code Online (Sandbox Code Playgroud) SqlConnection在事务中"登记"是什么意思?它只是意味着我在连接上执行的命令将参与事务吗?
如果是这样,在什么情况下SqlConnection会自动登记在环境TransactionScope事务中?
查看代码注释中的问题.我对每个问题的答案的猜测都在括号中的每个问题之后.
using (TransactionScope scope = new TransactionScope())
using (SqlConnection conn = ConnectToDB())
{
// Q1: Is connection automatically enlisted in transaction? (Yes?)
//
// Q2: If I open (and run commands on) a second connection now,
// with an identical connection string,
// what, if any, is the relationship of this second connection to the first?
//
// Q3: Will this second connection's automatic enlistment
// in the current transaction scope cause the transaction to …Run Code Online (Sandbox Code Playgroud)