EF6连接需要很长时间才能失败
作者:互联网
因此,我有一些标准的代码可以连接到数据库.
在创建的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秒的速度使连接失败,原因是它一直在旋转一个我似乎无法影响的过程,看起来像是重试策略,而没有任何回退,而之前触发了15次它放弃了,并调用我的MyConnectionStratagy来确定该怎么做.
有任何想法吗?我希望它第一次失败,不要继续尝试.
解决方法:
尝试添加连接超时= 5;如果要为所有后续命令增加连接字符串,请使用DbContext.Database.CommandTimeout = 60;
标签:entity-framework-6,c,entity-framework,sql-server 来源: https://codeday.me/bug/20191120/2047275.html