efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Conditional SelectMany cannot be translated

Open Xriuk opened this issue 8 months ago • 2 comments

Bug description

A SelectMany which flattens a collection conditionally on a given source cannot be translated. EF Playground

Your code

class Customer
{
    public int Id { get; set; }
    [MaxLength(512)]
    public string Name { get; set; }

    public Customer Associate { get; set; }
    public int AssociateId { get; set; } 
    public Customer Associated { get; set; }
    
    public List<Address> Addresses { get; set; }
}

class Address
{
    [MaxLength(256)]
    public string Name { get; set; }
    [MaxLength(256)]
    public string Line1 { get; set; }
    [MaxLength(256)]
    public string Line2 { get; set; }
    [MaxLength(85)]
    public string City { get; set; }
    [MaxLength(12)]
    public string ZipCode { get; set; }
    [MaxLength(128)]
    public string Country { get; set; }
}

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

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>().OwnsMany(e => e.Addresses);
        //modelBuilder.Entity<Customer>().HasOne(e => e.Associate).WithOne(e => e.Associated);
    }
}


context.Set<Customer>()
    .Where(c => c.Id == 3)
    .SelectMany(c => c.Name == "Test" ? c.Addresses : c.Associate.Addresses)
    .ToList();

Stack traces

Query failed The LINQ expression 'c => c.Name == "Test" ? c.Addresses : c.Associate.Addresses' 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.

EF Core version

8.0.14

Database provider

Microsoft.EntityFrameworkCore.SqlServer

Target framework

.NET 8.0

Xriuk avatar Apr 03 '25 10:04 Xriuk

this is a limitation of our navigation expansion logic. When processing SelectMany collection selector, we can only handle cases where the selecor itself is a NavigationExpansionExpression (e.g. c.Addresses or c.Associate.Addresses)

maumar avatar Apr 07 '25 04:04 maumar

related: https://github.com/dotnet/efcore/issues/32957

maumar avatar Apr 07 '25 04:04 maumar