Skip to content

Conditional SelectMany cannot be translated #35894

@Xriuk

Description

@Xriuk

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions