Database Timeout
1. 遇到的错误
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
---> Microsoft.Data.SqlClient.SqlException (0x80131904): Execution Timeout Expired.
The timeout period elapsed prior to completion of the operation or the server is not responding.
2. 查找原因
1) 命令超时&&连接超时
- Connection timeout (15 seconds by default)
- Command timeout (30 seconds by default)
https://learn.microsoft.com/en-us/troubleshoot/sql/database-engine/connect/timeout-expired-error
2) CommandTimeout
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.commandtimeout
The time in seconds to wait for the command to execute. The default is 30 seconds.
等待命令执行的时间(以秒为单位)。默认值为 30 秒。
3. 解决方案
1) 当未设置任何value的时候
_dbContext.Database.GetCommandTimeout() == null
2) 设置 CommandTimeout(秒)
// during your context setup
_dbContext.Database.SetCommandTimeout(180);
或者
// 在 Startup.cs 的 ConfigureServices 里面
// 添加 sqlServerOptions.CommandTimeout
services.AddDbContext<AppDbContext>(
options => options.UseLazyLoadingProxies()
.UseSqlServer(Configuration.GetConnectionString("AppConnectionString"),
sqlServerOptions => sqlServerOptions.CommandTimeout(180)));
3) 当设置Value之后
_dbContext.Database.GetCommandTimeout() == 180