問題描述
請看下面的代碼.如果我初始化多個實體上下文,那么我會在 僅第二組代碼 上得到以下異常.如果我注釋掉第二組就可以了.
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模板網!