Skip to content

Cosmos: ToList on structural collection property is treated as scalar in projection #38121

Closed

Description

@JoasE

Bug description

When calling ToList on a structural collection property within a projection, the collection is treated as a scalar collection. This causes the projection to happen on the sql side, and the generated materializer is a JsonConvert.Deserialize call, instead of a proper structural type materializer. Related: #34067

Your code

using Microsoft.EntityFrameworkCore;
using System.Diagnostics;


var options = new DbContextOptionsBuilder<MyDbContext>()
    .EnableSensitiveDataLogging()    .UseCosmos("AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==", "test")
    .LogTo(Console.WriteLine, Microsoft.Extensions.Logging.LogLevel.Information)
    .Options;

using var context = new MyDbContext(options);
await context.Database.EnsureDeletedAsync();
await context.Database.EnsureCreatedAsync();

var entity = new Customer
{
    Name = "Customer 1",
    NestedCollection = new List<NestedType>
    {
        new NestedType { Name = "Nested 1" },
    }
};

context.Customers.Add(entity);
await context.SaveChangesAsync();
context.ChangeTracker.Clear();

var structuralTypeCollectionToListQuery = await context.Customers
    .Select(c => c.NestedCollection.ToList())
    .SingleAsync(); // Returns List<NestedType> as scalar value (no materializer is ran, only JsonSerializer.Deserialize is ran... Any ef configs are ignored. 

Debug.Assert(structuralTypeCollectionToListQuery.First().Name == null); // Passes because the JSON is deserialized without any EF metadata

var structuralTypeCollectionQuery = await context.Customers
    .AsNoTracking()
    .Select(c => c.NestedCollection)
    .SingleAsync(); // Runs materializer

Debug.Assert(structuralTypeCollectionQuery.First().Name == "Nested 1"); // Passes because the materializer is ran

// This also allows certain query translations that shouldn't be possible
var structuralTypeCollectionDistinctToListQuery = await context.Customers
    .Select(c => c.NestedCollection.Distinct().ToList())
    .SingleAsync(); // Returns List<NestedType> as scalar value (no materializer is ran, only JsonSerializer.Deserialize is ran... Any ef configs are ignored.

Debug.Assert(structuralTypeCollectionDistinctToListQuery.First().Name == null); // Passes because the JSON is deserialized without any EF metadata

var structuralTypeCollectionDistinctQuery = await context.Customers
    .AsNoTracking()
    .Select(c => c.NestedCollection.Distinct())
    .SingleAsync(); // Throws ArgumentException (should actaully be NotTranslatedException? But that is something else)

public class MyDbContext(DbContextOptions options) : DbContext(options)
{
    public DbSet<Customer> Customers { get; set; } = null!;

    protected override void OnModelCreating(ModelBuilder builder)
        => builder.Entity<Customer>(
            b =>
            {
                b.OwnsMany(x => x.NestedCollection, cfg => cfg.Property(x => x.Name).ToJsonProperty("custom_name"));
            });
}
public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }

    public List<NestedType> NestedCollection { get; set; }
}

public class NestedType
{
    public int Id { get; set; }

    public string Name { get; set; }
}

Stack traces


Verbose output


EF Core version

10.0.0

Database provider

Microsoft.EntityFrameworkCore.Cosmos

Target framework

.NET 10

Operating system

W11

IDE

VS2026

Activity

  1. JoasE commented on Apr 16, 2026

    @JoasE
    ContributorAuthor

    I think I have a solution for this, changing CosmosProjectionBindingExpressionVisitor to only produce projection bindings if the translated subquery results in a scalar. But I am not completely sure this is the correct solution.
    I ran into this while working on cosmos deserialization and think that #34067 should actually fix this, producing a CollectionShaperExpression? But haven't looked into that

  2. self-assigned this
    on Apr 16, 2026
  3. added theissue type on Apr 16, 2026
  4. added this to the 11.0.0 milestone on Apr 16, 2026
  5. changed the title [-]Cosmos: ToList on structural collection property is treaded as scalar in projection[/-] [+]Cosmos: ToList on structural collection property is treated as scalar in projection[/+] on Apr 16, 2026
  6. modified the milestones: 11.0.0, Backlog on Jun 9, 2026
  7. added a commit that references this issue on Jun 10, 2026
    68e50ba
  8. modified the milestones: Backlog, 11.0.0 on Jun 10, 2026
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

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions