# Microsoft.EntityFrameworkCore.Query.QueryCompilationException：编译查询时发生异常。请查看 InnerException 获取详细信息。

- **ID:** `dotnet/ef-core-query-compilation-failed`
- **领域:** dotnet
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

EF Core 的查询管道无法将 LINQ 表达式转换为 SQL，原因是支持的操作，例如 Where 子句中的自定义方法调用或复杂的客户端评估。

## 版本兼容性

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

## 解决方案

1. ```
   重写查询，仅使用 EF Core 支持的函数。例如，将 'Where(x => MyHelper.Calculate(x.Value) > 10)' 替换为 'Where(x => x.Value > 10)' 或使用计算列。
   ```
2. ```
   在不支持的操作前使用 .ToList()，然后继续使用 LINQ to Objects：var list = context.Entities.Where(e => e.IsActive).ToList(); var result = list.Where(e => MyHelper.Calculate(e.Value) > 10);
   ```

## 无效尝试

- **** — This pulls the entire table into memory, causing performance issues and potential OutOfMemoryException. (70% 失败率)
- **** — This introduces SQL injection risks and loses the type safety of LINQ. (90% 失败率)
