在EF项目中使用System.Transactions时,我应该考虑哪些事项?

时间:2012-07-18 18:25:22

标签: entity-framework transactions isolation-level

背景

我有一个MVC应用程序和一个Windows服务,它访问使用EntityFramework的相同数据访问库。 Windows服务监视多个表上的某些活动并执行一些计算。

我们正在对数百个数据库使用DAL项目,在运行时为上下文生成连接字符串。

我们有许多函数(包括调用EF实体的存储过程和.NET方法),由于我们使用的数据范围非常密集,因此可能会相互阻塞。

问题

Windows服务不是那么重要,它不能等待。如果必须阻止某些东西,Windows服务可以。之前我发现了一些SO问题,指出System.Transactions是将事务隔离级别设置为READ UNCOMMITTED以最小化锁定的方法。

我试过了,我可能误解了发生的事情,所以我需要澄清一下。

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)

我可以假设我不应该在使用块中调用多个查询?第一个查询返回正常。这是一次在一个数据库上执行(实际上其他实例正在不同的线程中运行,并且此线程中的任何内容都不会触及其他线程。)

我的问题是,这应该如何使用,还是我应该知道更多?

注意:这是一个监控功能,因此必须重复运行。

1 个答案:

答案 0 :(得分:1)

在您的代码中,您正在使用事务范围。看起来第一个查询使用轻量级db事务。当第二个查询到来时,事务范围将事务升级为分布式事务。

分布式事务使用MSDTC。

这是错误发生的地方,默认情况下未启用MSDTC。即使启用并启动它,也需要将其配置为允许远程客户端创建分布式事务。