Repository navigation
Description
Bug description
When querying an entity that contains a complex property mapped to JSON via .ComplexProperty(..., b => b.ToJson()) using AsNoTrackingWithIdentityResolution(), projecting the complex property (either in an anonymous type projection Select(u => new { u.Id, u.Address }) or a MemberInit projection Select(u => new User { Id = u.Id, Address = u.Address })) fails during query compilation with:
System.InvalidCastException: Unable to cast object of type 'Microsoft.EntityFrameworkCore.Metadata.RuntimeComplexType' to type 'Microsoft.EntityFrameworkCore.Metadata.IEntityType'.
What we found proof for
-
Trigger conditions:
- An entity contains a complex property mapped to JSON (
b.ComplexProperty(u => u.Address, ab => ab.ToJson())). - The query specifies
QueryTrackingBehavior.NoTrackingWithIdentityResolution(or.AsNoTrackingWithIdentityResolution()). - The projection selects the complex property directly (
u.Address), generating aStructuralTypeShaperExpression.
- An entity contains a complex property mapped to JSON (
-
Contrast matrix (scenarios that succeed):
- Tracking queries succeed:
db.Users.Select(u => new { u.Id, u.Address }).ToList()works as expected. - Standard non-tracking queries succeed:
db.Users.AsNoTracking().Select(u => new { u.Id, u.Address }).ToList()works as expected. - Table-mapped complex properties succeed: If the complex property is table-mapped (without
.ToJson()),AsNoTrackingWithIdentityResolution().Select(u => new { u.Id, u.Address })works as expected. - Complex collections succeed: If mapped as
b.ComplexCollection(u => u.Phones, pb => pb.ToJson()),AsNoTrackingWithIdentityResolution().Select(u => new { u.Id, u.Phones })works as expected. - Manual member reconstruction succeeds:
Select(u => new User { Id = u.Id, Address = new Address { City = u.Address.City } })works because it projects scalar leaf properties into a new client-side instance instead of shaping the complex type fromJsonProjectionInfo.
- Tracking queries succeed:
-
Source code defect:
InRelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs, the private classJsonCorrectOrderOfEntitiesForChangeTrackerValidatorvisitsStructuralTypeShaperExpression:case JsonProjectionInfo jsonEntityProjectionInfo: { var jsonEntityType = (IEntityType)entityShaperExpression.StructuralType;
For JSON-mapped complex properties,
entityShaperExpression.StructuralTypeis an instance ofRuntimeComplexType(implementingIComplexType), notIEntityType. This unchecked cast causes the exception.
What we suspect or reasoned about
JsonCorrectOrderOfEntitiesForChangeTrackerValidator was introduced to prevent data corruption when populating the change tracker in NoTrackingWithIdentityResolution mode (see #35468). Unlike entities, complex types are value objects without identity and do not participate in identity resolution in the change tracker.
In the same method, collection projections (line 3788) are guarded:
case JsonProjectionInfo jsonCollectionProjectionInfo
when collectionResultExpression.StructuralProperty is INavigation navigation:Guarding the StructuralTypeShaperExpression branch with if (entityShaperExpression.StructuralType is IEntityType jsonEntityType) (skipping complex types) appears to be the intended behavior.
Your code
#:property PublishAot=false
#:package Microsoft.EntityFrameworkCore.Sqlite@10.0.13
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using var db = new AppDbContext();
db.Database.OpenConnection();
db.Database.EnsureCreated();
db.Users.Add(new User { Address = new Address { City = "Paris" } });
db.SaveChanges();
// Throws System.InvalidCastException: Unable to cast object of type 'Microsoft.EntityFrameworkCore.Metadata.RuntimeComplexType'
// to type 'Microsoft.EntityFrameworkCore.Metadata.IEntityType'.
var result = db.Users
.AsNoTrackingWithIdentityResolution()
.Select(u => new { u.Id, u.Address })
.ToList();
Console.WriteLine($"Found {result.Count} users");
public class User
{
public int Id { get; set; }
public Address Address { get; set; } = null!;
}
public class Address
{
public string City { get; set; } = null!;
}
public class AppDbContext : DbContext
{
public DbSet<User> Users => Set<User>();
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseSqlite("DataSource=:memory:");
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>(b =>
{
b.ComplexProperty(u => u.Address, ab => ab.ToJson());
});
}
}Stack traces
System.InvalidCastException: Unable to cast object of type 'Microsoft.EntityFrameworkCore.Metadata.RuntimeComplexType' to type 'Microsoft.EntityFrameworkCore.Metadata.IEntityType'.
at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.JsonCorrectOrderOfEntitiesForChangeTrackerValidator.VisitExtension(Expression extensionExpression)
at System.Dynamic.Utils.ExpressionVisitorUtils.VisitArguments(ExpressionVisitor visitor, IArgumentProvider nodes)
at System.Linq.Expressions.ExpressionVisitor.VisitNew(NewExpression node)
at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.JsonCorrectOrderOfEntitiesForChangeTrackerValidator.Validate(Expression expression)
at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.ProcessShaper(Expression shaperExpression, Expression& relationalCommandResolver, IReadOnlyList`1& readerColumns, LambdaExpression& relatedDataLoaders, Int32& collectionId)
at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.VisitShapedQuery(ShapedQueryExpression shapedQueryExpression)
at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.VisitExtension(Expression extensionExpression)
at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.VisitExtension(Expression extensionExpression)
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.Execute[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
Verbose output
No response
EF Core version
10.0.13 (verified on 10.0.13 and 10.0.0; defect also verified in main branch at commit babe09db33)
Database provider
Microsoft.EntityFrameworkCore.Sqlite (also reproduces with Npgsql.EntityFrameworkCore.PostgreSQL; the defect resides in shared relational query compilation Microsoft.EntityFrameworkCore.Relational)
Target framework
.NET 10.0
Operating system
Windows 11
IDE
No response
Activity
[-]Using a JSON-mapped complex property with AsNoTrackingWithIdentityResolution throws InvalidCastException[/-][+]Projecting a JSON-mapped complex property with AsNoTrackingWithIdentityResolution throws InvalidCastException[/+]bkoelman commentedon Oct 17, 2026
Related: the reason why we are forced to use
AsNoTrackingWithIdentityResolutionis explained at dotnet/EntityFramework.Docs#2205 (comment).Fix JSON complex property projections with identity resolution (dotne…
Remove EF Core bypass for compound attributes in query projection
Remove EF Core bypass for compound attributes in query projection
--all
[release/10.0] Fix JSON complex property projections with identity re…
--all
--all
--all
Reconcile tree with pre-linearization branch state
Compound and collection attributes
Compound and collection attributes
Compound and collection attributes
Compound and collection attributes