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

Open
#39,351 5 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 2 days

@buzztouniverse is already working on this.

Since Oct 21, 2026.

  • #39433 by @buzztouniverse — closed without merging

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
48/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
csharp
Domain
databases

Research direction

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.

Written by the indexing model from the issue text.

Description

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

Dominant language
C#
Stars
14.8k
Forks
3.5k
Avg merge
3d 7h
Merged PRs (30d)
182

Getting set up

Open in Codespaces

Starts the project's dev container in your browser, under your own GitHub account.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from dotnet/efcore

All issues in dotnet/efcore

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.