dotnet runtime_error ai_generated true

Microsoft.EntityFrameworkCore.Query.QueryCompilationException: An exception occurred while compiling the query. See InnerException for details.

ID: dotnet/ef-core-query-compilation-failed

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
1Evidence
2023-04-18First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
EF Core 6.0 active
EF Core 7.0 active
EF Core 8.0 active

Root Cause

EF Core's query pipeline fails to translate a LINQ expression into SQL due to unsupported operations, such as custom method calls in Where clauses or complex client-side evaluation.

generic

中文

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

Official Documentation

https://learn.microsoft.com/en-us/ef/core/querying/client-eval

Workarounds

  1. 85% success Rewrite the query to use only EF Core-supported functions. For example, replace 'Where(x => MyHelper.Calculate(x.Value) > 10)' with 'Where(x => x.Value > 10)' or use a computed column.
    Rewrite the query to use only EF Core-supported functions. For example, replace 'Where(x => MyHelper.Calculate(x.Value) > 10)' with 'Where(x => x.Value > 10)' or use a computed column.
  2. 75% success Use .ToList() before the unsupported operation and continue with LINQ to Objects: var list = context.Entities.Where(e => e.IsActive).ToList(); var result = list.Where(e => MyHelper.Calculate(e.Value) > 10);
    Use .ToList() before the unsupported operation and continue with LINQ to Objects: var list = context.Entities.Where(e => e.IsActive).ToList(); var result = list.Where(e => MyHelper.Calculate(e.Value) > 10);

中文步骤

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

Dead Ends

Common approaches that don't work:

  1. 70% fail

    This pulls the entire table into memory, causing performance issues and potential OutOfMemoryException.

  2. 90% fail

    This introduces SQL injection risks and loses the type safety of LINQ.