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

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

## 根因

SQL 查询执行超过配置的命令超时时间，通常由大数据量、缺少索引或 Entity Framework Core 生成的低效 LINQ 查询引起。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 6.0 | active | — | — |
| 7.0 | active | — | — |
| 8.0 | active | — | — |
| 9.0 | active | — | — |

## 解决方案

1. ```
   通过早期添加 .Where() 过滤器和使用 .Select() 投影仅需要的列来优化 LINQ 查询。示例：var data = context.Orders.Where(o => o.Date > DateTime.UtcNow.AddDays(-30)).Select(o => new { o.Id, o.Total }).ToList();
   ```
2. ```
   在 WHERE、JOIN 和 ORDER BY 子句中使用的列上添加数据库索引。使用 SQL Server Management Studio 或 EF Core 迁移：CREATE INDEX IX_Orders_Date ON Orders (Date);
   ```
3. ```
   临时增加特定操作的 CommandTimeout：context.Database.SetCommandTimeout(120); 或在连接字符串中："Command Timeout=120;"
   ```

## 无效尝试

- **Increasing CommandTimeout to a very high value (e.g., 300 seconds) without optimizing the query** — Temporary fix that masks the underlying performance issue; query may still time out under heavy load or with larger datasets. (70% 失败率)
- **Adding .AsNoTracking() to all queries without understanding if tracking is needed** — AsNoTracking improves performance for read-only queries but does not fix inefficient joins or missing indexes. (50% 失败率)
- **Splitting the query into multiple smaller queries without using .Include() properly** — Multiple round trips can increase total execution time and cause N+1 query problems, worsening performance. (65% 失败率)
