[英]Error: The underlying provider failed on Open. How to resolve it?
我的功能类似于以下代码:
using(var db = new MyDbContext())
{
//a whole bunch of code, db is working.
//then I try opening another DbContext like so
using(var dba = new AnotherDbContext())
{
//about 2 lines of code just to get something from a database
}
}
然后,当我到达第二个DbContext时,我收到2条错误消息:
“底层提供程序在Open上失败。” &“服务器'myserver'上的MSDTC不可用。”
有人知道发生这种情况的原因吗? 我可以一次打开2个DbContext吗?
在第一种情况下,您将嵌套AnotherDbContext 。 将为每个数据库打开与数据库的连接。 当您在using块中调用服务方法时,将在MyDbContext中打开一个新连接,而另外一个已经打开。 这会导致您的事务升级为分布式事务,并且外部连接无法使用部分提交的数据(该服务中dba.SaveChanges调用的结果)。 还要注意,分布式事务的速度要慢得多,因此降低性能的副作用。
private void btnTwoConnectionsNested_Click(object sender, EventArgs e)
{
string connectionString = @"Data Source=" + tbServer.Text
+ @";Initial Catalog=master;Integrated Security=True; timeout=0";
using (TransactionScope transactionScope = new TransactionScope())
{
SqlConnection connectionOne = new SqlConnection(connectionString);
SqlConnection connectionTwo = new SqlConnection(connectionString);
try
{
//2 connections, nested
connectionOne.Open();
connectionTwo.Open(); // escalates to DTC on 05 and 08
connectionTwo.Close();
connectionOne.Close();
MessageBox.Show("Success");
}
catch (Exception ex)
{
MessageBox.Show("ERROR: " + ex.Message);
}
finally
{
connectionOne.Dispose();
connectionTwo.Dispose();
}
}
}
在一个事务范围内,它将打开两个嵌套的连接。 结果:
针对SQL Server 2005实例:服务器“ SERVERNAME”上的MSDTC不可用。
针对SQL Server 2008实例:
服务器“ SERVERNAME”上的MSDTC不可用。
对于两个版本的嵌套连接,SQL Server都(并且应该)升级为DTC。
嵌套连接将在SQL Server 2005和2008中升级为DTC。一次打开一个连接将在2005年升级为DTC,但在2008年不会升级。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.