15

我正在使用最新的 v6 实体框架和 UnitOfWork 模式。在过去的几年中,这在服务器上一直很好。

我想迁移到 Azure 托管并使用 SQLAzure,因此开始迁移应用程序。但是我遇到了很多问题。

首先,我间歇性地收到此错误

从服务器接收结果时发生传输级错误。

经过一些谷歌搜索,这似乎很常见,您需要实现自己的SqlAzureExecutionStrategy- 一切似乎都很好。直到我发现它不支持发起的交易!

然后我偶然发现了这篇博文 - 它概述了确切的问题并提供了如何解决问题的示例代码(或者我认为)。

我完全按照帖子(据我所知)。我有我的 dBconfiguration 类设置,它在应用程序启动时触发了 SetExecutionStrategy。

public class EfConfig : DbConfiguration
{
    public EfConfig()
    {
        SetExecutionStrategy("System.Data.SqlClient", () => SuspendExecutionStrategy
              ? (IDbExecutionStrategy)new DefaultExecutionStrategy()
              : new CustomSqlAzureExecutionStrategy());
    }

    public static bool SuspendExecutionStrategy
    {
        get { return (bool?)CallContext.LogicalGetData("SuspendExecutionStrategy") ?? false; }
        set { CallContext.LogicalSetData("SuspendExecutionStrategy", value); }
    }
}

然后我有一个上面引用的名为“CustomSqlAzureExecutionStrategy”的自定义类,我把它放在下面并覆盖了ShouldRetryOn方法

public class CustomSqlAzureExecutionStrategy : SqlAzureExecutionStrategy
{
    protected override bool ShouldRetryOn(Exception exception)
    {
        var shouldRetry = false;

        var sqlException = exception as SqlException;
        if (sqlException != null)
        {
            foreach (SqlError error in sqlException.Errors)
            {
                if (error.Number == -2)
                {
                    shouldRetry = true;   
                }

            }
        }
        shouldRetry = shouldRetry || base.ShouldRetryOn(exception);
        return shouldRetry;
    }
}

但是,当我运行我的应用程序时,我仍然遇到与开始时相同的错误,但这次只是指向自定义类?

配置的执行策略“CustomSqlAzureExecutionStrategy”不支持用户发起的事务。

我在这里错过了什么明显的东西吗?或者不明白什么?任何帮助将不胜感激。

更新


通常... StackOverFlow 橡皮闪避。我实际上正确地阅读了它,发现我需要SuspendExecutionStrategy在我的 UnitOfWork 中手动设置(BeginTransaction 之前和 Commit 之后)。

所以我之前有这个.BeginTransaction()

EfConfig.SuspendExecutionStrategy = true;

就在这之后.Commit()

EfConfig.SuspendExecutionStrategy = false;

这允许我现在运行应用程序,但我仍然(很少我可能会添加)收到暂时错误消息?

从服务器接收结果时发生传输级错误。

4

2 回答 2

3

除了暂停执行策略之外,您还需要包装您正在重试的操作,包括手动调用执行策略中的事务,请参阅我对如何使用 SqlAzureExecutionStrategy 和“Nolock”的回答

于 2015-08-19T17:58:51.207 回答
2

确保将整个内容包装在 try/finally 中,以确保将挂起标志设置回 false。还可以查看此链接以获取详细说明: 帮助链接

于 2015-11-25T06:08:04.357 回答