c# - EF6 连接需要很长时间才能失败

标签 c# sql-server entity-framework entity-framework-6

所以我有一些代码可以连接到数据库,非常标准。

在创建的 DbContext 中,我尝试查询一个表。

当我创建 DbContext 时,我输入了一些不存在的 url,而不是实际的数据库 url。

所以我预计此时会失败,问题是,我不能让它失败的速度超过 30 秒。

我从 System.Data.SqlClient.SqlInternalConnection

得到了一堆第一次更改异常

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)

我尝试创建一个自定义的 DbConfiguration 和 DbExecutionPolicy,但是直到它尝试连接很多次之后才被​​调用。

public class InternalsDbConfiguration : DbConfiguration
{
    public InternalsDbConfiguration()
    {
        this.SetExecutionStrategy("System.Data.SqlClient", () =>
        {
            var r = new MyExecutionStrategy();
            return r;
        });
    }
}

public class MyExecutionStrategy : DbExecutionStrategy
{
    protected override bool ShouldRetryOn(Exception exception)
    {
        var s = exception as SqlException;
        if (s == null)
            return false;
        if (s.Number == 53)
            return false;
        return true;
    }
}

我只是不能让连接失败的速度超过 30 秒,因为它一直在经历一些我似乎无法影响的过程,看起来像是一个没有任何后退的重试策略,就像在它放弃并调用我的 MyConnectionStratagy 以弄清楚要做什么之前 15 次。

有什么想法吗?我希望它第一次失败而不是继续尝试。

最佳答案

尝试将 Connection Timeout=5; 添加到连接字符串,如果要为所有后续命令增加,请使用 DbContext.Database.CommandTimeout = 60;

关于c# - EF6 连接需要很长时间才能失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27852476/

相关文章:

c# - Azure 类库访问 GetConfigurationSettingValue 与 web.config

sql-server - SQL Server : how can I get the correct DB size from sys. master_files?

sql - 如何有效地反转多对多 SQL 查询?

c# - 如何调整 DatagramSocket.MessageReceived 以与异步/等待一起使用?

c# - .Net MVC 4 使用 Windows 身份验证 - 重定向未经授权的用户

c# - 使用 OpenIdConnectServer 并尝试通过 API 服务连接到 Facebook

sql - 4 列复合索引是否有益于 3 列查询?

c# - EF6 : Configure complex mapping for entities (code first)

c# - Entity Framework Core 2.0 中的迁移 - 如何指定环境或传递参数

linq-to-sql - 幕后的 linq2sql 等于 Entity Framework 吗