Query: `The LINQ expression 'p' could not be translated` when `Any` predicate compares parameter with expression referencing parameter (e.g. `p => p == p.ToUpper()`)

未关闭
#39,351 5 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 2 天内回复

@buzztouniverse 已经在做这个了。

开始于 2026年10月21日。

  • #39433 来自 @buzztouniverse —— 已关闭,未合并

评估

难度
4/5
预计耗时
3-5 天
新手友好度
48/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
csharp
领域
databases

调研方向

Start in QueryOptimizingExpressionVisitor.cs at the Any predicate normalization shown in the issue, then trace how the normalized expression reaches relational Contains translation. Check existing query optimizer tests for Any and primitive collections; add a regression case for a predicate whose non-parameter operand still references the lambda parameter. Done when that query translates successfully and existing normalization cases remain covered.

由索引模型根据 Issue 内容生成。

描述

area-primitive-collections area-query customer-reported
Bug description

When filtering a primitive collection with an equality comparison where one operand is the lambda parameter p and the other operand is an expression that also references p (for example, .Any(p => p == p.ToUpper())), query compilation fails with:

System.InvalidOperationException: The LINQ expression 'p' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'.
Root cause:

In Microsoft.EntityFrameworkCore.Query.Internal.QueryOptimizingExpressionVisitor:

// Normalize x.Any(i => i == foo) to x.Contains(foo)
// And x.All(i => i != foo) to !x.Contains(foo)
if (methodCallExpression.Method.IsGenericMethod
    && (methodInfo == EnumerableMethods.AnyWithPredicate || ...)
    && methodCallExpression.Arguments[1].UnwrapLambdaFromQuote() is var lambda
    && TryExtractEqualityOperands(lambda.Body, out var left, out var right, out var negated))
{
    var itemExpression = left == lambda.Parameters[0]
        ? right
        : right == lambda.Parameters[0]
            ? left
            : null;

    if (itemExpression is not null)
    {
        var containsMethodDefinition = methodInfo.DeclaringType == typeof(Enumerable)
            ? EnumerableMethods.Contains
            : QueryableMethods.Contains;

        if ((methodInfo == EnumerableMethods.AnyWithPredicate || methodInfo == QueryableMethods.AnyWithPredicate) && !negated)
        {
            var containsMethod = containsMethodDefinition.MakeGenericMethod(methodCallExpression.Method.GetGenericArguments()[0]);
            return Expression.Call(null, containsMethod, methodCallExpression.Arguments[0], itemExpression);
        }
        ...

When left == lambda.Parameters[0] evaluates to true (e.g. left is p), itemExpression is assigned right (in this case p.ToUpper()).
However, the visitor does not check whether itemExpression still references lambda.Parameters[0].

Because of this, EF Core normalizes:

b.Tags.Any(p => p == p.ToUpper())

into:

b.Tags.Contains(p.ToUpper())

The parameter p has now leaked outside of any lambda scope. Later, when relational translation attempts to translate Contains(p.ToUpper()), RelationalSqlTranslatingExpressionVisitor.VisitParameter encounters the unbound parameter p and fails with the exception above.

Applicability to EF Core 11 (RC / main branch):

Checking QueryOptimizingExpressionVisitor.cs in the main branch confirms that this code remains unchanged. Therefore, this issue also applies to EF Core 11 (currently in RC).

Workaround:

Using string.Compare(p, p.ToUpper()) == 0 prevents QueryOptimizingExpressionVisitor from attempting the rewrite to Contains, and EF Core translates the Any subquery to SQL without issues.

Your code
#:property PublishAot=false
#:package [email protected]

using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;

using var connection = new SqliteConnection("DataSource=:memory:");
await connection.OpenAsync();

var options = new DbContextOptionsBuilder<MyDbContext>()
    .UseSqlite(connection)
    .Options;

using var context = new MyDbContext(options);
await context.Database.EnsureCreatedAsync();

context.Blogs.Add(new Blog { Tags = ["csharp", "DOTNET"] });
await context.SaveChangesAsync();

// Workaround works fine:
var workaroundResult = await context.Blogs
    .Where(b => b.Tags.Any(p => string.Compare(p, p.ToUpper()) == 0))
    .ToListAsync();

Console.WriteLine($"Workaround returned {workaroundResult.Count} blog(s).");

// Throws System.InvalidOperationException: The LINQ expression 'p' could not be translated.
var failingResult = await context.Blogs
    .Where(b => b.Tags.Any(p => p == p.ToUpper()))
    .ToListAsync();

Console.WriteLine($"Failing query returned {failingResult.Count} blog(s).");

public class MyDbContext(DbContextOptions<MyDbContext> options) : DbContext(options)
{
    public DbSet<Blog> Blogs => Set<Blog>();
}

public class Blog
{
    public int Id { get; set; }
    public List<string> Tags { get; set; } = [];
}
Stack traces
System.InvalidOperationException: The LINQ expression 'p' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.VisitParameter(ParameterExpression parameterExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Sqlite.Query.Internal.SqliteSqlTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.TranslateInternal(Expression expression, Boolean applyDefaultTypeMapping)
   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.Translate(Expression expression, Boolean applyDefaultTypeMapping)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateExpression(Expression expression, Boolean applyDefaultTypeMapping)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateContains(ShapedQueryExpression source, Expression item)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.Translate(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.TranslateSubquery(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.<VisitMethodCall>g__TranslateAsSubquery|31_0(Expression expression, <>c__DisplayClass31_0&)
   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Sqlite.Query.Internal.SqliteSqlTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.TranslateInternal(Expression expression, Boolean applyDefaultTypeMapping)
   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.Translate(Expression expression, Boolean applyDefaultTypeMapping)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateExpression(Expression expression, Boolean applyDefaultTypeMapping)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateLambdaExpression(ShapedQueryExpression shapedQueryExpression, LambdaExpression lambdaExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateWhere(ShapedQueryExpression source, LambdaExpression predicate)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.Translate(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutorExpression[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass11_0`1.<ExecuteCore>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteCore[TResult](Expression query, Boolean async, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync[TResult](Expression query, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.ExecuteAsync[TResult](Expression expression, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetAsyncEnumerator(CancellationToken cancellationToken)
   at System.Runtime.CompilerServices.ConfiguredCancelableAsyncEnumerable`1.GetAsyncEnumerator()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
Verbose output

EF Core version

10.0.13 (and EF Core 11 in RC / main)

Database provider

Microsoft.EntityFrameworkCore.Sqlite (also affects Npgsql.EntityFrameworkCore.PostgreSQL and other relational providers)

Target framework

.NET 10.0

Operating system

Windows 11

IDE

Visual Studio 2026 / VS Code / Cursor

主要语言
C#
星标
14.8k
派生
3.5k
平均合并
3 天 7 小时
30 天内合并 PR
182

环境准备

在 Codespaces 中打开

在浏览器里用你自己的 GitHub 账号启动这个项目的开发容器。

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

dotnet/efcore 的其他 Issue

查看 dotnet/efcore 的全部 Issue

相似的 Issue

更多 C# Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。