简体   繁体   English

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

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

I am using Entity Framework and my connection string looks something like this -我正在使用实体框架,我的连接字符串看起来像这样 -

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

I have set the connection timeout as 2 sec and most of the time this code works and I got error within 2 sec if the connection is down.我已将连接超时设置为 2 秒,并且大多数情况下此代码都有效,如果连接断开,我会在 2 秒内出错。 But on rare occasions, this timeout happens after 25 to 30 secs as you can see in the below log, the error occurred after 23 secs-但在极少数情况下,此超时发生在 25 到 30 秒后,正如您在下面的日志中看到的那样,错误发生在 23 秒后 -

Aug 30 07:13:07 Save begins. 8 月 30 日 07:13:07 保存开始。

Aug 30 07:13:30 Error - A network-related or instance-specific error occurred while establishing a connection to SQL Server. 8 月 30 日 07:13:30 错误 - 与 SQL 服务器建立连接时发生与网络相关或特定于实例的错误。 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.验证实例名称是否正确,并且 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) (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)

The code is written something like that-代码是这样写的——

Log.Info("Save begins.")

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

Log.Info("Save Ends.")

I am not able to find the reason of this delay as it happens very occasionally.我无法找到这种延迟的原因,因为它偶尔会发生。 Can you please help me to understand what could be the possible reasons of this behavior?您能否帮助我了解这种行为的可能原因是什么?

Try to set connection timeout directly to your DbContext class while instantiating it.尝试在实例化时直接将连接超时设置为 DbContext class。

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

After that, try your query again.之后,再次尝试您的查询。

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

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