# Microsoft.Data.SqlClient.SqlException (0x80131904): 执行超时已过期。操作完成之前超时时间已到或服务器未响应。

- **ID:** `dotnet/ef-core-sql-timeout`
- **领域:** dotnet
- **类别:** data_error
- **错误码:** `-2146232060`
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

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

## 版本兼容性

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

## 解决方案

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

## 无效尝试

- **Set CommandTimeout to 0 (infinite) in DbContext options** — Infinite timeout can cause indefinite hangs and resource exhaustion; it masks the underlying query performance issue. (70% 失败率)
- **Add .AsNoTracking() to all queries** — AsNoTracking reduces overhead but does not fix slow queries; timeout still occurs if the query is slow due to missing indexes. (85% 失败率)
- **Increase SqlCommand timeout in appsettings** — Increasing timeout without optimizing the query or adding indexes only delays the failure; the query may still fail under load. (60% 失败率)
