Query: `The LINQ expression 'p' could not be translated` when `Any` predicate compares parameter with expression referencing parameter (e.g. `p => p == p.ToUpper()`)
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
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
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
Starts the project's dev container in your browser, under your own GitHub account.
- No Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from dotnet/efcore
-
customer-reported
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
Maintainers usually reply within 2 days
-
GroupBy element `OrderBy(...).First()`/`MaxBy` over an owned type mapped to its own table fails to translatePossibly taken @cincuranet claimed this today. Openarea-groupby area-query
Difficulty 4/5 3-5 days Newbie friendliness 25/100
dotnet/efcore#39833 · 1 assignee ·
Maintainers usually reply within 2 days
-
SQLite: Polygon.Length translates to GLength, which returns 0Possibly taken @cincuranet claimed this today. Openarea-query area-sqlite
Difficulty 3/5 1-2 days Newbie friendliness 45/100
dotnet/efcore#39826 · 1 assignee ·
Maintainers usually reply within 2 days
-
Migration lock with LockReleaseBehavior.Transaction doesn't prevent concurrent migrations since per-migration transactionsPossibly taken @AndriySvyryd claimed this 1 day ago. Openarea-migrations
dotnet/efcore#39824 · 1 assignee ·
Maintainers usually reply within 2 days
-
Querying a TPC base type with a JSON complex property throwsPossibly taken @cincuranet claimed this 1 day ago. Openarea-query
Difficulty 4/5 3-5 days Newbie friendliness 22/100
dotnet/efcore#39814 · 1 assignee ·
Maintainers usually reply within 2 days
Similar issues
-
Difficulty 2/5 1-3 hours Newbie friendliness 77/100
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
SubtitleEdit/subtitleedit#17247 ·
Maintainers usually reply within 1 day
-
Restore test cleanup fails on Windows when restored files are read-onlyPossibly taken @JamBalaya56562 claimed this today. Open
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
duplicati/duplicati#8046 · 1 comment ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 70/100
Maintainers usually reply within 1 day
-
Bundles Documentation
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
pyrevitlabs/pyRevit#4285 ·
Maintainers usually reply within 1 day