背景
我有一个MVC应用程序和一个Windows服务,访问相同的数据访问库,利用EntityFramework。 Windows服务监视几个表上的某些活动并执行一些计算。在我的EF项目中使用System.Transactions时应该考虑什么?
我们使用的是DAL项目对几百个数据库,生成在运行时环境的连接字符串。
我们有许多功能(存储过程和.NET方法,其对EF实体调用),这是因为我们使用的数据的范围非常密集分贝具有阻止彼此的潜力。
问题
windows服务不是那么重要,它不能等待。如果某些东西必须被阻止,那么Windows服务可以。早些时候,我发现了很多SO问题,它们指出,在将事务隔离级别设置为READ UNCOMMITTED以最小化锁定时,需要使用System.Transactions
。
我想这一点,我可能会误解是怎么回事,所以我需要一些澄清。
在Windows服务的方法的结构,像这样:
private bool _stopMe = false;
public void Update()
{
EntContext context = new EntContext();
do
{
var transactionOptions = new System.Transactions.TransactionOptions();
transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
using (var transactionScope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOptions))
{
List<Ent1> myEnts = (from e....Complicated query here).ToList();
SomeCalculations(myEnts);
List<Ent2> myOtherEnts = (from e... Complicated query using entities from previous query here).ToList();
MakeSomeChanges(myOtherEnts);
context.SaveChanges();
}
Thread.Sleep(5000); //wait 5 seconds before allow do block to continue
}while (! _stopMe)
}
当我执行我的第二个查询,一个异常被抛出:
The underlying provider failed on Open.
Network access for Distributed Transaction Manager (MSDTC) has been disabled. Please
enable DTC for network access in the security configuration for MSDTC using the
Component Services Administrative tool.
The transaction manager has disabled its support for remote/network
transactions. (Exception from HRESULT: 0x8004D024)
我认为我不应该叫该使用块中有多个查询?第一个查询返回就好了。这是一次在一个数据库上执行的(其他实例正在不同的线程中运行,并且此线程中的任何内容都不会触及其他实例)。
我的问题是,这是它应该如何使用,或者是有更多的这个,我应该知道吗?
注:这是一个监控功能,所以必须反复运行。
您使用的是DbContext还是ObjectContext?您当前的问题可能存在,因为您让EF控制数据库连接的生存期,因此它最可能为每个查询使用不同的连接 - 这需要分布式事务。顺便说一句。你的交易永远不会提交。 – 2012-07-18 20:59:17
我正在使用DbContext。我想知道如何更密切地控制我在EntityFramework中的连接。至于承诺交易,这可能源于我对交易的大量误解。今天是我第一次使用System.Transaction,所以我现在还不太快。 – CodeWarrior 2012-07-18 21:31:25
检查[这篇文章](http://blogs.msdn.com/b/diego/archive/2012/01/26/exception-from-dbcontext-api-entityconnection-can-only-be-constructed-with-a - 封闭 - DBConnection进行。aspx) - 它讨论了如何控制DbContext API中连接的生命周期。 – 2012-07-18 21:44:29