Skip to content

Projecting a JSON-mapped complex property with AsNoTrackingWithIdentityResolution throws InvalidCastException #39322

Closed

Description

@bkoelman

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

  1. 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 a StructuralTypeShaperExpression.
  2. 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 from JsonProjectionInfo.
  3. Source code defect:
    In RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.cs, the private class JsonCorrectOrderOfEntitiesForChangeTrackerValidator visits StructuralTypeShaperExpression:

    case JsonProjectionInfo jsonEntityProjectionInfo:
    {
        var jsonEntityType = (IEntityType)entityShaperExpression.StructuralType;

    For JSON-mapped complex properties, entityShaperExpression.StructuralType is an instance of RuntimeComplexType (implementing IComplexType), not IEntityType. 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

  1. changed the title [-]Using a JSON-mapped complex property with AsNoTrackingWithIdentityResolution throws InvalidCastException[/-] [+]Projecting a JSON-mapped complex property with AsNoTrackingWithIdentityResolution throws InvalidCastException[/+] on Oct 17, 2026
  2. bkoelman commented on Oct 17, 2026

    @bkoelman
    ContributorAuthor

    Related: the reason why we are forced to use AsNoTrackingWithIdentityResolution is explained at dotnet/EntityFramework.Docs#2205 (comment).

  3. added theissue type on Oct 22, 2026
  4. added this to the 12.0.0 milestone on Oct 22, 2026
  5. self-assigned this
    on Oct 22, 2026
  6. added a commit that references this issue on Oct 30, 2026
    f29db88
  7. added a commit that references this issue on Nov 16, 2026
  8. added a commit that references this issue on Nov 16, 2026
    39e202b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions