-2146232060 dotnet data_error ai_generated true

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

其他格式: JSON · Markdown 中文 · English
85%修复率
88%置信度
1证据数
2023-06-01首次发现

版本兼容性

版本状态引入弃用备注
.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.

generic

官方文档

https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlexception

解决方案

  1. 在 WHERE 和 JOIN 子句使用的列上添加数据库索引。示例:CREATE INDEX IX_Orders_CustomerId ON Orders (CustomerId);
  2. 在 OnConfiguring 中将 CommandTimeout 设置为更高值(如 120 秒):optionsBuilder.UseSqlServer(connectionString, opts => opts.CommandTimeout(120));
  3. 使用 .AsSplitQuery() 优化 LINQ 查询以避免笛卡尔爆炸:context.Orders.Include(o => o.Details).AsSplitQuery().ToList();

无效尝试

常见但无效的做法:

  1. 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.

  2. 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.

  3. 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.