ASP.NET Core SQL 连接超时

Joh*_*ter 7 entity-framework-core asp.net-core-mvc asp.net-core asp.net-core-1.0

我一直致力于将 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)  
Run Code Online (Sandbox Code Playgroud)

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

public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
    this.Database.SetCommandTimeout(120);
}
Run Code Online (Sandbox Code Playgroud)

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

app.ApplicationServices.GetService<ApplicationDbContext>().Database.Migrate();
Run Code Online (Sandbox Code Playgroud)

Mik*_*ind 8

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

Server=(localdb)\mssqllocaldb;Database=yourDb;Trusted_connection=true;connect timeout=100;
Run Code Online (Sandbox Code Playgroud)