Bug description
I noticed the following behavior when upgrading a .NET 10 app from EF Core 8 to EF Core 10. I think this is a regression introduced in EF Core 9 that still persists in EF Core 10.
This kind of query works normally
var query = db.Blogs
.Where(b => b.PublishedOn >= DateTime.Today.AddDays(EF.Constant(-lookbackDays)))
but breaks when compiled/wrapped in EF.CompileAsyncQuery. EF Core 9 throws InvalidCastException, casting to ParameterExpression while EF Core 10 tries to cast to QueryParameterExpression
The same exceptions are thrown if I replace the variable -lookbackDays with a literal constant, e.g. -10. I think this is provider agnostic, because I noticed this behavior with Npgsql but made a repro based on SQLite.
I attached a full single-file runnable repro below.
Expected behavior
Either:
- the compiled query works, as in EF Core 8 / like the equivalent non-compiled query, or
- EF throws a clear supported exception explaining that this pattern is not supported in compiled queries.
Actual behavior
EF Core 9 throws:
System.InvalidCastException: Unable to cast object of type 'System.Linq.Expressions.ConstantExpression' to type 'System.Linq.Expressions.ParameterExpression'.
EF Core 10 throws:
System.InvalidCastException: Unable to cast object of type 'System.Linq.Expressions.ConstantExpression' to type 'Microsoft.EntityFrameworkCore.Query.QueryParameterExpression'.
The stack trace goes through QueryableMethodNormalizingExpressionVisitor during query compilation.
Notes
- EF Core 8: works
- EF Core 9/10: equivalent non-compiled query works, compiled query throws
- SQLite repro, but this looks provider-agnostic since the exception is thrown before query execution
Your code
#!/usr/bin/env dotnet
#:property TargetFramework=net10.0
#:property PublishAot=false
// #:package Microsoft.EntityFrameworkCore.Sqlite@8.*
// #:package Microsoft.EntityFrameworkCore.Sqlite@9.*
#:package Microsoft.EntityFrameworkCore.Sqlite@10.*
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
var lookbackDays = 7; // intentionally not const
const string url = "https://example.com";
Console.WriteLine($"Runtime: {Environment.Version}");
Console.WriteLine($"EF Core: {typeof(DbContext).Assembly.GetName().Version}");
Console.WriteLine($"Provider: {typeof(SqliteDbContextOptionsBuilderExtensions).Assembly.GetName().Version}");
Console.WriteLine($"Days: {lookbackDays}");
Console.WriteLine();
await using var connection = new SqliteConnection("Data Source=:memory:");
await connection.OpenAsync();
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlite(connection)
.EnableDetailedErrors()
.EnableSensitiveDataLogging()
.LogTo(Console.WriteLine,
new[]
{
DbLoggerCategory.Query.Name,
DbLoggerCategory.Database.Command.Name,
DbLoggerCategory.Infrastructure.Name,
},
LogLevel.Information)
.Options;
AppDbContext NewDb() => new(options);
await using (var db = NewDb())
{
await db.Database.EnsureCreatedAsync();
db.Blogs.AddRange(
new Blog { Id = 1, Url = url, PublishedOn = DateTime.Today.AddDays(-2) },
new Blog { Id = 2, Url = url, PublishedOn = DateTime.Today.AddDays(-7) },
new Blog { Id = 3, Url = url, PublishedOn = DateTime.Today.AddDays(-20) });
await db.SaveChangesAsync();
}
await NormalQuery();
await CompiledBroken();
async Task NormalQuery()
{
Banner("1) Normal query works");
await using var db = NewDb();
var query = db.Blogs
.TagWith("normal")
.Where(b => b.Url == url)
.Where(b => b.PublishedOn >= DateTime.Today.AddDays(EF.Constant(-lookbackDays)))
.OrderBy(b => b.Id);
Console.WriteLine(query.ToQueryString());
PrintRows(await query.ToListAsync());
}
async Task CompiledBroken()
{
Banner("2) Compiled query throws");
Func<AppDbContext, string, IAsyncEnumerable<Blog>> compiled = EF.CompileAsyncQuery(
(AppDbContext db, string blogUrl) => db.Blogs
.TagWith("compiled-broken")
.Where(b => b.Url == blogUrl)
.Where(b => b.PublishedOn >= DateTime.Today.AddDays(EF.Constant(-lookbackDays)))
.OrderBy(b => b.Id)
.Select(b => b));
await using var db = NewDb();
await TryAsync(async () =>
{
var rows = new List<Blog>();
await foreach (var blog in compiled(db, url))
{
rows.Add(blog);
}
PrintRows(rows);
});
}
static void Banner(string title)
{
Console.WriteLine(new string('=', title.Length));
Console.WriteLine(title);
Console.WriteLine(new string('=', title.Length));
}
static void PrintRows(List<Blog> rows)
{
Console.WriteLine($"Rows: {rows.Count}");
foreach (var blog in rows)
{
Console.WriteLine($" {blog.Id}: {blog.Url} @ {blog.PublishedOn:yyyy-MM-dd}");
}
Console.WriteLine();
}
static async Task TryAsync(Func<Task> action)
{
try
{
await action();
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.WriteLine();
}
}
sealed class Blog
{
public int Id { get; set; }
public string Url { get; set; } = "";
public DateTime PublishedOn { get; set; }
}
sealed class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
public DbSet<Blog> Blogs => Set<Blog>();
}
Stack traces
EF 8 - works
PS D:\git\efconstant-mwe-min> dotnet run --file EfConstantCompiledBlog.cs
Runtime: 10.0.5
EF Core: 8.0.26.0
Provider: 8.0.26.0
Days: 7
warn: 21.04.2026 15:07:36.330 CoreEventId.SensitiveDataLoggingEnabledWarning[10400] (Microsoft.EntityFrameworkCore.Infrastructure)
Sensitive data logging is enabled. Log entries and exception messages may include sensitive application data; this mode should only be enabled during development.
info: 21.04.2026 15:07:36.687 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (25ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT COUNT(*) FROM "sqlite_master" WHERE "type" = 'table' AND "rootpage" IS NOT NULL;
info: 21.04.2026 15:07:36.946 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (5ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE "Blogs" (
"Id" INTEGER NOT NULL CONSTRAINT "PK_Blogs" PRIMARY KEY AUTOINCREMENT,
"Url" TEXT NOT NULL,
"PublishedOn" TEXT NOT NULL
);
info: 21.04.2026 15:07:37.372 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (8ms) [Parameters=[@p0='1', @p1='2026-04-19T00:00:00.0000000+02:00' (DbType = DateTime), @p2='https://example.com' (Nullable = false) (Size = 19)], CommandType='Text', CommandTimeout='30']
INSERT INTO "Blogs" ("Id", "PublishedOn", "Url")
VALUES (@p0, @p1, @p2);
info: 21.04.2026 15:07:37.385 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (0ms) [Parameters=[@p0='2', @p1='2026-04-14T00:00:00.0000000+02:00' (DbType = DateTime), @p2='https://example.com' (Nullable = false) (Size = 19)], CommandType='Text', CommandTimeout='30']
INSERT INTO "Blogs" ("Id", "PublishedOn", "Url")
VALUES (@p0, @p1, @p2);
info: 21.04.2026 15:07:37.386 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (0ms) [Parameters=[@p0='3', @p1='2026-04-01T00:00:00.0000000+02:00' (DbType = DateTime), @p2='https://example.com' (Nullable = false) (Size = 19)], CommandType='Text', CommandTimeout='30']
INSERT INTO "Blogs" ("Id", "PublishedOn", "Url")
VALUES (@p0, @p1, @p2);
=====================
1) Normal query works
=====================
-- normal
SELECT "b"."Id", "b"."PublishedOn", "b"."Url"
FROM "Blogs" AS "b"
WHERE "b"."Url" = 'https://example.com' AND "b"."PublishedOn" >= rtrim(rtrim(strftime('%Y-%m-%d %H:%M:%f', 'now', 'localtime', 'start of day', CAST(CAST(-7 AS REAL) AS TEXT) || ' days'), '0'), '.')
ORDER BY "b"."Id"
info: 21.04.2026 15:07:37.987 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
-- normal
SELECT "b"."Id", "b"."PublishedOn", "b"."Url"
FROM "Blogs" AS "b"
WHERE "b"."Url" = 'https://example.com' AND "b"."PublishedOn" >= rtrim(rtrim(strftime('%Y-%m-%d %H:%M:%f', 'now', 'localtime', 'start of day', CAST(CAST(-7 AS REAL) AS TEXT) || ' days'), '0'), '.')
ORDER BY "b"."Id"
Rows: 2
1: https://example.com @ 2026-04-19
2: https://example.com @ 2026-04-14
========================
2) Compiled query throws
========================
info: 21.04.2026 15:07:38.187 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (0ms) [Parameters=[@__blogUrl='https://example.com' (Size = 19)], CommandType='Text', CommandTimeout='30']
-- compiled-broken
SELECT "b"."Id", "b"."PublishedOn", "b"."Url"
FROM "Blogs" AS "b"
WHERE "b"."Url" = @__blogUrl AND "b"."PublishedOn" >= rtrim(rtrim(strftime('%Y-%m-%d %H:%M:%f', 'now', 'localtime', 'start of day', CAST(CAST(-7 AS REAL) AS TEXT) || ' days'), '0'), '.')
ORDER BY "b"."Id"
Rows: 2
1: https://example.com @ 2026-04-19
2: https://example.com @ 2026-04-14
EF 9 - throws ParameterExpression
PS D:\git\efconstant-mwe-min> dotnet run --file EfConstantCompiledBlog.cs
Runtime: 10.0.5
EF Core: 9.0.15.0
Provider: 9.0.15.0
Days: 7
warn: 21.04.2026 15:07:50.161 CoreEventId.SensitiveDataLoggingEnabledWarning[10400] (Microsoft.EntityFrameworkCore.Infrastructure)
Sensitive data logging is enabled. Log entries and exception messages may include sensitive application data; this mode should only be enabled during development.
info: 21.04.2026 15:07:50.358 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (15ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT COUNT(*) FROM "sqlite_master" WHERE "type" = 'table' AND "rootpage" IS NOT NULL;
info: 21.04.2026 15:07:50.575 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (2ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE "Blogs" (
"Id" INTEGER NOT NULL CONSTRAINT "PK_Blogs" PRIMARY KEY AUTOINCREMENT,
"Url" TEXT NOT NULL,
"PublishedOn" TEXT NOT NULL
);
info: 21.04.2026 15:07:50.845 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (7ms) [Parameters=[@p0='1', @p1='2026-04-19T00:00:00.0000000+02:00' (DbType = DateTime), @p2='https://example.com' (Nullable = false) (Size = 19)], CommandType='Text', CommandTimeout='30']
INSERT INTO "Blogs" ("Id", "PublishedOn", "Url")
VALUES (@p0, @p1, @p2);
info: 21.04.2026 15:07:50.855 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (0ms) [Parameters=[@p0='2', @p1='2026-04-14T00:00:00.0000000+02:00' (DbType = DateTime), @p2='https://example.com' (Nullable = false) (Size = 19)], CommandType='Text', CommandTimeout='30']
INSERT INTO "Blogs" ("Id", "PublishedOn", "Url")
VALUES (@p0, @p1, @p2);
info: 21.04.2026 15:07:50.856 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (0ms) [Parameters=[@p0='3', @p1='2026-04-01T00:00:00.0000000+02:00' (DbType = DateTime), @p2='https://example.com' (Nullable = false) (Size = 19)], CommandType='Text', CommandTimeout='30']
INSERT INTO "Blogs" ("Id", "PublishedOn", "Url")
VALUES (@p0, @p1, @p2);
=====================
1) Normal query works
=====================
-- normal
SELECT "b"."Id", "b"."PublishedOn", "b"."Url"
FROM "Blogs" AS "b"
WHERE "b"."Url" = 'https://example.com' AND "b"."PublishedOn" >= rtrim(rtrim(strftime('%Y-%m-%d %H:%M:%f', 'now', 'localtime', 'start of day', CAST(CAST(-7 AS REAL) AS TEXT) || ' days'), '0'), '.')
ORDER BY "b"."Id"
info: 21.04.2026 15:07:51.437 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
-- normal
SELECT "b"."Id", "b"."PublishedOn", "b"."Url"
FROM "Blogs" AS "b"
WHERE "b"."Url" = 'https://example.com' AND "b"."PublishedOn" >= rtrim(rtrim(strftime('%Y-%m-%d %H:%M:%f', 'now', 'localtime', 'start of day', CAST(CAST(-7 AS REAL) AS TEXT) || ' days'), '0'), '.')
ORDER BY "b"."Id"
Rows: 2
1: https://example.com @ 2026-04-19
2: https://example.com @ 2026-04-14
========================
2) Compiled query throws
========================
System.InvalidCastException: Unable to cast object of type 'System.Linq.Expressions.ConstantExpression' to type 'System.Linq.Expressions.ParameterExpression'.
at Microsoft.EntityFrameworkCore.Query.Internal.QueryableMethodNormalizingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at System.Linq.Expressions.ExpressionVisitor.VisitUnary(UnaryExpression node)
at System.Dynamic.Utils.ExpressionVisitorUtils.VisitArguments(ExpressionVisitor visitor, IArgumentProvider nodes)
at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryableMethodNormalizingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at System.Linq.Expressions.ExpressionVisitor.VisitBinary(BinaryExpression node)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryableMethodNormalizingExpressionVisitor.VisitBinary(BinaryExpression binaryExpression)
at System.Linq.Expressions.ExpressionVisitor.VisitLambda[T](Expression`1 node)
at System.Linq.Expressions.ExpressionVisitor.VisitUnary(UnaryExpression node)
at System.Dynamic.Utils.ExpressionVisitorUtils.VisitArguments(ExpressionVisitor visitor, IArgumentProvider nodes)
at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryableMethodNormalizingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at System.Dynamic.Utils.ExpressionVisitorUtils.VisitArguments(ExpressionVisitor visitor, IArgumentProvider nodes)
at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryableMethodNormalizingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at System.Dynamic.Utils.ExpressionVisitorUtils.VisitArguments(ExpressionVisitor visitor, IArgumentProvider nodes)
at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryableMethodNormalizingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryableMethodNormalizingExpressionVisitor.Normalize(Expression expression)
at Microsoft.EntityFrameworkCore.Query.QueryTranslationPreprocessor.NormalizeQueryableMethod(Expression expression)
at Microsoft.EntityFrameworkCore.Query.RelationalQueryTranslationPreprocessor.NormalizeQueryableMethod(Expression expression)
at Microsoft.EntityFrameworkCore.Query.QueryTranslationPreprocessor.Process(Expression query)
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.CreateCompiledAsyncQuery[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledAsyncEnumerableQuery`2.CreateCompiledQuery(IQueryCompiler queryCompiler, Expression expression)
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryBase`2.<>c.<EnsureExecutor>b__7_0(CompiledQueryBase`2 t, TContext c, LambdaExpression q)
at Microsoft.EntityFrameworkCore.Internal.NonCapturingLazyInitializer.EnsureInitialized[TParam1,TParam2,TParam3,TValue](TValue& target, TParam1 param1, TParam2 param2, TParam3 param3, Func`4 valueFactory)
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryBase`2.EnsureExecutor(TContext context)
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryBase`2.ExecuteCore(TContext context, CancellationToken cancellationToken, Object[] parameters)
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryBase`2.ExecuteCore(TContext context, Object[] parameters)
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledAsyncEnumerableQuery`2.Execute[TParam1](TContext context, TParam1 param1)
at Program.<>c__DisplayClass0_1.<<<Main>$>b__14>d.MoveNext() in D:\git\efconstant-mwe-min\EfConstantCompiledBlog.cs:line 84
--- End of stack trace from previous location ---
at Program.<<Main>$>g__TryAsync|0_5(Func`1 action) in D:\git\efconstant-mwe-min\EfConstantCompiledBlog.cs:line 113
EF 10 - throws QueryParameterExpression
PS D:\git\efconstant-mwe-min> dotnet run --file EfConstantCompiledBlog.cs
Runtime: 10.0.5
EF Core: 10.0.6.0
Provider: 10.0.6.0
Days: 7
warn: 21.04.2026 15:08:32.731 CoreEventId.SensitiveDataLoggingEnabledWarning[10400] (Microsoft.EntityFrameworkCore.Infrastructure)
Sensitive data logging is enabled. Log entries and exception messages may include sensitive application data; this mode should only be enabled during development.
info: 21.04.2026 15:08:32.951 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (19ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT COUNT(*) FROM "sqlite_master" WHERE "type" = 'table' AND "rootpage" IS NOT NULL;
info: 21.04.2026 15:08:33.234 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (3ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE "Blogs" (
"Id" INTEGER NOT NULL CONSTRAINT "PK_Blogs" PRIMARY KEY AUTOINCREMENT,
"Url" TEXT NOT NULL,
"PublishedOn" TEXT NOT NULL
);
info: 21.04.2026 15:08:33.644 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (11ms) [Parameters=[@p0='1', @p1='2026-04-19T00:00:00.0000000+02:00' (DbType = DateTime), @p2='https://example.com' (Nullable = false) (Size = 19)], CommandType='Text', CommandTimeout='30']
INSERT INTO "Blogs" ("Id", "PublishedOn", "Url")
VALUES (@p0, @p1, @p2);
info: 21.04.2026 15:08:33.659 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (0ms) [Parameters=[@p0='2', @p1='2026-04-14T00:00:00.0000000+02:00' (DbType = DateTime), @p2='https://example.com' (Nullable = false) (Size = 19)], CommandType='Text', CommandTimeout='30']
INSERT INTO "Blogs" ("Id", "PublishedOn", "Url")
VALUES (@p0, @p1, @p2);
info: 21.04.2026 15:08:33.660 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (0ms) [Parameters=[@p0='3', @p1='2026-04-01T00:00:00.0000000+02:00' (DbType = DateTime), @p2='https://example.com' (Nullable = false) (Size = 19)], CommandType='Text', CommandTimeout='30']
INSERT INTO "Blogs" ("Id", "PublishedOn", "Url")
VALUES (@p0, @p1, @p2);
=====================
1) Normal query works
=====================
-- normal
SELECT "b"."Id", "b"."PublishedOn", "b"."Url"
FROM "Blogs" AS "b"
WHERE "b"."Url" = 'https://example.com' AND "b"."PublishedOn" >= rtrim(rtrim(strftime('%Y-%m-%d %H:%M:%f', 'now', 'localtime', 'start of day', CAST(CAST(-7 AS REAL) AS TEXT) || ' days'), '0'), '.')
ORDER BY "b"."Id"
info: 21.04.2026 15:08:34.301 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
-- normal
SELECT "b"."Id", "b"."PublishedOn", "b"."Url"
FROM "Blogs" AS "b"
WHERE "b"."Url" = 'https://example.com' AND "b"."PublishedOn" >= rtrim(rtrim(strftime('%Y-%m-%d %H:%M:%f', 'now', 'localtime', 'start of day', CAST(CAST(-7 AS REAL) AS TEXT) || ' days'), '0'), '.')
ORDER BY "b"."Id"
Rows: 2
1: https://example.com @ 2026-04-19
2: https://example.com @ 2026-04-14
========================
2) Compiled query throws
========================
System.InvalidCastException: Unable to cast object of type 'System.Linq.Expressions.ConstantExpression' to type 'Microsoft.EntityFrameworkCore.Query.QueryParameterExpression'.
at Microsoft.EntityFrameworkCore.Query.Internal.QueryableMethodNormalizingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at System.Linq.Expressions.ExpressionVisitor.VisitUnary(UnaryExpression node)
at System.Dynamic.Utils.ExpressionVisitorUtils.VisitArguments(ExpressionVisitor visitor, IArgumentProvider nodes)
at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryableMethodNormalizingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at System.Linq.Expressions.ExpressionVisitor.VisitBinary(BinaryExpression node)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryableMethodNormalizingExpressionVisitor.VisitBinary(BinaryExpression binaryExpression)
at System.Linq.Expressions.ExpressionVisitor.VisitLambda[T](Expression`1 node)
at System.Linq.Expressions.ExpressionVisitor.VisitUnary(UnaryExpression node)
at System.Dynamic.Utils.ExpressionVisitorUtils.VisitArguments(ExpressionVisitor visitor, IArgumentProvider nodes)
at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryableMethodNormalizingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at System.Dynamic.Utils.ExpressionVisitorUtils.VisitArguments(ExpressionVisitor visitor, IArgumentProvider nodes)
at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryableMethodNormalizingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at System.Dynamic.Utils.ExpressionVisitorUtils.VisitArguments(ExpressionVisitor visitor, IArgumentProvider nodes)
at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryableMethodNormalizingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryableMethodNormalizingExpressionVisitor.Normalize(Expression expression)
at Microsoft.EntityFrameworkCore.Query.QueryTranslationPreprocessor.NormalizeQueryableMethod(Expression expression)
at Microsoft.EntityFrameworkCore.Query.RelationalQueryTranslationPreprocessor.NormalizeQueryableMethod(Expression expression)
at Microsoft.EntityFrameworkCore.Query.QueryTranslationPreprocessor.Process(Expression query)
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.CreateCompiledAsyncQuery[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledAsyncEnumerableQuery`2.CreateCompiledQuery(IQueryCompiler queryCompiler, Expression expression)
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryBase`2.<>c.<EnsureExecutor>b__7_0(CompiledQueryBase`2 t, TContext c, LambdaExpression q)
at Microsoft.EntityFrameworkCore.Internal.NonCapturingLazyInitializer.EnsureInitialized[TParam1,TParam2,TParam3,TValue](TValue& target, TParam1 param1, TParam2 param2, TParam3 param3, Func`4 valueFactory)
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryBase`2.EnsureExecutor(TContext context)
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryBase`2.ExecuteCore(TContext context, CancellationToken cancellationToken, Object[] parameters)
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryBase`2.ExecuteCore(TContext context, Object[] parameters)
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledAsyncEnumerableQuery`2.Execute[TParam1](TContext context, TParam1 param1)
at Program.<>c__DisplayClass0_1.<<<Main>$>b__14>d.MoveNext() in D:\git\efconstant-mwe-min\EfConstantCompiledBlog.cs:line 84
--- End of stack trace from previous location ---
at Program.<<Main>$>g__TryAsync|0_5(Func`1 action) in D:\git\efconstant-mwe-min\EfConstantCompiledBlog.cs:line 113
Verbose output
n/a
EF Core version
10.0.6
Database provider
Microsoft.EntityFrameworkCore.Sqlite (but I think this is provider agnostic)
Target framework
.NET 10.0
Operating system
Windows 11
IDE
Bug description
I noticed the following behavior when upgrading a .NET 10 app from EF Core 8 to EF Core 10. I think this is a regression introduced in EF Core 9 that still persists in EF Core 10.
This kind of query works normally
but breaks when compiled/wrapped in
EF.CompileAsyncQuery. EF Core 9 throwsInvalidCastException, casting toParameterExpressionwhile EF Core 10 tries to cast toQueryParameterExpressionThe same exceptions are thrown if I replace the variable
-lookbackDayswith a literal constant, e.g.-10. I think this is provider agnostic, because I noticed this behavior with Npgsql but made a repro based on SQLite.I attached a full single-file runnable repro below.
Expected behavior
Either:
Actual behavior
EF Core 9 throws:
EF Core 10 throws:
The stack trace goes through
QueryableMethodNormalizingExpressionVisitorduring query compilation.Notes
Your code
Stack traces
EF 8 - works
EF 9 - throws
ParameterExpressionEF 10 - throws
QueryParameterExpressionVerbose output
n/a
EF Core version
10.0.6
Database provider
Microsoft.EntityFrameworkCore.Sqlite (but I think this is provider agnostic)
Target framework
.NET 10.0
Operating system
Windows 11
IDE