efcore
efcore copied to clipboard
Conditional SelectMany cannot be translated
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
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)
related: https://github.com/dotnet/efcore/issues/32957