请看下面的代码.如果我初始化多个实体上下文,那么我会在 仅第二组代码 上得到以下异常.如果我注释掉第二组就可以了.
See the code below. If I initialize more than one entity context, then I get the following exception on the 2nd set of code only. If I comment out the second set it works.
{"底层提供程序在打开时失败."}
{"The underlying provider failed on Open."}
内部:{与底层事务管理器的通信失败."}
Inner: {"Communication with the underlying transaction manager has failed."}
内部:{错误 HRESULT E_FAIL 已从对 COM 组件的调用返回."}
Inner: {"Error HRESULT E_FAIL has been returned from a call to a COM component."}
请注意,这是一个示例应用程序,我知道连续创建 2 个上下文没有意义.但是,生产代码确实有理由在同一个 TransactionScope
中创建多个上下文,并且这是无法更改的.
Note that this is a sample app and I know it doesn't make sense to create 2 contexts in a row. However, the production code does have reason to create multiple contexts in the same TransactionScope
, and this cannot be changed.
编辑
这是我之前尝试设置 MS-DTC 的一个问题.它似乎在服务器和客户端上都启用了.我不确定它是否设置正确.另请注意,我尝试这样做的原因之一是 TransactionScope
中的现有代码使用 ADO.NET 和 Linq 2 Sql...我希望它们也使用相同的事务.(这听起来可能很疯狂,但如果可能的话,我需要让它发挥作用).
Here is a previous question of me trying to set up MS-DTC. It seems to be enabled on both the server and the client. I'm not sure if it is set up correctly. Also note that one of the reasons I am trying to do this, is that existing code within the TransactionScope
uses ADO.NET and Linq 2 Sql... I would like those to use the same transaction also. (That probably sounds crazy, but I need to make it work if possible).
如何在 C# 中使用 TransactionScope?
解决方案
Windows 防火墙阻止了与 MS-DTC 的连接.
using(TransactionScope ts = new System.Transactions.TransactionScope())
{
using (DatabaseEntityModel o = new DatabaseEntityModel())
{
var v = (from s in o.Advertiser select s).First();
v.AcceptableLength = 1;
o.SaveChanges();
}
//-> By commenting out this section, it works
using (DatabaseEntityModel o = new DatabaseEntityModel())
{
//Exception on this next line
var v = (from s1 in o.Advertiser select s1).First(); v.AcceptableLength = 1;
o.SaveChanges();
}
//->
ts.Complete();
}
由于某种原因,您的 MS-DTC(分布式事务协调器)无法正常工作.MS-DTC用于协调跨多个异构资源的事务结果,包括多个sql连接.
Your MS-DTC (Distributed transaction co-ordinator) is not working properly for some reason. MS-DTC is used to co-ordinate the results of transactions across multiple heterogeneous resources, including multiple sql connections.
看看此链接了解有关正在发生的事情的更多信息.
Take a look at this link for more info on what is happening.
基本上,如果您确保 MS-DTC 正在运行并且正常工作,那么使用 2 个 ADO.NET 连接应该没有问题 - 无论它们是实体框架连接还是任何其他类型.
Basically if you make sure your MS-DTC is running and working properly you should have no problems with using 2 ADO.NET connections - whether they are entity framework connections or any other type.
这篇关于为什么 TransactionScope 不适用于实体框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!