【问题标题】:ASP.NET Core SQL Connection TImeoutASP.NET Core SQL 连接超时
【发布时间】:2016-09-12 17:47:35
【问题描述】:

我一直致力于将 ASP.NET 5 RC1 应用程序升级到 ASP.NET Core 1。我通过替换包(AspNet 到 AspNetCore)并从 EF7 更改为 EF Core(Microsoft.Data.Entity)成功升级了它到 Microsoft.EntityFrameworkCore)。

我遇到的问题是连接超时已过期的间歇性 SqlException。

这里是完整的例外:

System.Data.SqlClient.SqlException occurred.  
Class=11 ErrorCode=-2146232060 HResult=-2146232060 LineNumber=0  
**Message=Connection Timeout Expired.  The timeout period elapsed while attempting to consume the pre-login handshake acknowledgement.  This could be because the pre-login handshake failed or the server was unable to respond back in time.  The duration spent while attempting to connect to this server was - [Pre-Login] initialization=924; handshake=6;**   
  Number=-2   
  Procedure=""  
  Server=(localdb)\mssqllocaldb  
  Source=.Net SqlClient Data Provider  
  State=0  
  StackTrace:  
       at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)  

我试过像这样增加命令超时:

public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
    this.Database.SetCommandTimeout(120);
}

该行抛出异常,但是当我将其注释掉时,它会在其他地方发生,这使我相信它在第一次访问数据库时发生。

app.ApplicationServices.GetService<ApplicationDbContext>().Database.Migrate();

【问题讨论】:

  • 现在没有问题还是什么?在此之后this.Database.SetCommandTimeout(120);
  • 添加超时后问题仍然存在。

标签: asp.net-core asp.net-core-mvc entity-framework-core asp.net-core-1.0


【解决方案1】:

您的问题与与服务器建立连接所需的时间有关。更改CommandTimeout 值(允许命令执行的时间量)不会对此产生任何影响。您需要考虑增加 connection timeout 值,这是通过连接字符串实现的:

Server=(localdb)\mssqllocaldb;Database=yourDb;Trusted_connection=true;connect timeout=100;

【讨论】:

  • 你知道为什么我升级到 Core 1.0 之后才遇到这个问题吗?
  • 它与实体框架的版本无关。该问题纯粹与 SQL Server 的响应能力有关。 LocalDb 按需启动。我不知道哪些因素会影响 LocalDb 准备就绪所需的时间,但您使用的 EF 或 .NET 版本极不可能是其中之一。
猜你喜欢
  • 1970-01-01
  • 2021-01-11
  • 2021-11-12
  • 2016-06-20
  • 2020-07-08
  • 1970-01-01
  • 1970-01-01
  • 2023-02-22
  • 2021-09-02
相关资源
最近更新 更多