繁体   English   中英

连接超时并不总是使用实体框架工作

[英]Connection timeout is not always working using Entity Framework

我正在使用实体框架,我的连接字符串看起来像这样 -

Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;Connection Timeout=2

我已将连接超时设置为 2 秒,并且大多数情况下此代码都有效,如果连接断开,我会在 2 秒内出错。 但在极少数情况下,此超时发生在 25 到 30 秒后,正如您在下面的日志中看到的那样,错误发生在 23 秒后 -

8 月 30 日 07:13:07 保存开始。

8 月 30 日 07:13:30 错误 - 与 SQL 服务器建立连接时发生与网络相关或特定于实例的错误。 服务器未找到或无法访问。 验证实例名称是否正确,并且 SQL 服务器配置为允许远程连接。 (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)- at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword , Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken)

代码是这样写的——

Log.Info("Save begins.")

try{
  Context.SaveChanges();
}
catch(
  Log.Info($"ERROR - + {ex.Message}-{ex.StackTrace}");
)

Log.Info("Save Ends.")

我无法找到这种延迟的原因,因为它偶尔会发生。 您能否帮助我了解这种行为的可能原因是什么?

尝试在实例化时直接将连接超时设置为 DbContext class。

var context = new Context("connection string");
(context as IObjectContextAdapter).ObjectContext.CommandTimeout = 2;

之后,再次尝试您的查询。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM