-2146232060 dotnet data_error ai_generated true

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

Also available as: JSON · Markdown · 中文
85%Fix Rate
88%Confidence
1Evidence
2023-06-01First Seen

Version Compatibility

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

Root Cause

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

中文

Entity Framework Core 查询或命令因复杂联接、未索引查询或结果集过大而超过默认的 30 秒命令超时。

Official Documentation

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

Workarounds

  1. 90% success Add database indexes on columns used in WHERE and JOIN clauses. Example: CREATE INDEX IX_Orders_CustomerId ON Orders (CustomerId);
    Add database indexes on columns used in WHERE and JOIN clauses. Example: CREATE INDEX IX_Orders_CustomerId ON Orders (CustomerId);
  2. 75% success Set CommandTimeout to a higher value (e.g., 120 seconds) in OnConfiguring: optionsBuilder.UseSqlServer(connectionString, opts => opts.CommandTimeout(120));
    Set CommandTimeout to a higher value (e.g., 120 seconds) in OnConfiguring: optionsBuilder.UseSqlServer(connectionString, opts => opts.CommandTimeout(120));
  3. 85% success Optimize LINQ query by using .AsSplitQuery() to avoid Cartesian explosion: context.Orders.Include(o => o.Details).AsSplitQuery().ToList();
    Optimize LINQ query by using .AsSplitQuery() to avoid Cartesian explosion: context.Orders.Include(o => o.Details).AsSplitQuery().ToList();

中文步骤

  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();

Dead Ends

Common approaches that don't work:

  1. Set CommandTimeout to 0 (infinite) in DbContext options 70% fail

    Infinite timeout can cause indefinite hangs and resource exhaustion; it masks the underlying query performance issue.

  2. Add .AsNoTracking() to all queries 85% fail

    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% fail

    Increasing timeout without optimizing the query or adding indexes only delays the failure; the query may still fail under load.