Microsoft.Data.SqlClient.SqlException (0x80131904): 执行超时已过期。操作完成之前超时时间已到或服务器未响应。
Microsoft.Data.SqlClient.SqlException (0x80131904): Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
ID: dotnet/ef-core-sql-timeout
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| .NET 6.0 | active | — | — | — |
| .NET 7.0 | active | — | — | — |
| .NET 8.0 | active | — | — | — |
| EF Core 6.0 | active | — | — | — |
| EF Core 7.0 | active | — | — | — |
| EF Core 8.0 | active | — | — | — |
根因分析
Entity Framework Core 查询或命令因复杂联接、未索引查询或结果集过大而超过默认的 30 秒命令超时。
English
Entity Framework Core query or command exceeds the default 30-second command timeout due to complex joins, unindexed queries, or large result sets in SQL Server.
官方文档
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlexception解决方案
-
在 WHERE 和 JOIN 子句使用的列上添加数据库索引。示例:CREATE INDEX IX_Orders_CustomerId ON Orders (CustomerId);
-
在 OnConfiguring 中将 CommandTimeout 设置为更高值(如 120 秒):optionsBuilder.UseSqlServer(connectionString, opts => opts.CommandTimeout(120));
-
使用 .AsSplitQuery() 优化 LINQ 查询以避免笛卡尔爆炸:context.Orders.Include(o => o.Details).AsSplitQuery().ToList();
无效尝试
常见但无效的做法:
-
Set CommandTimeout to 0 (infinite) in DbContext options
70% 失败
Infinite timeout can cause indefinite hangs and resource exhaustion; it masks the underlying query performance issue.
-
Add .AsNoTracking() to all queries
85% 失败
AsNoTracking reduces overhead but does not fix slow queries; timeout still occurs if the query is slow due to missing indexes.
-
Increase SqlCommand timeout in appsettings
60% 失败
Increasing timeout without optimizing the query or adding indexes only delays the failure; the query may still fail under load.