1 year ago
#316796
Doc
Ef core linq fails to translate to SQL while querying table per hierarchy base type
I have 3 classes like this (clearly this is a simplification)
public enum MyTypeEnum
{
A,
B
}
public abstract class Base
{
public int Id { get; set; }
public int Description { get; set; }
public MyTypeEnum Type { get; set; }
}
public class ClassA : Base
{
public bool IsTrue { get; set; }
}
public class ClassB : Base
{
public double Amount { get; set; }
}
and my db context is like this
public class MyDbContext : DbContext
{
public DbSet<Base> Base { get; set; }
public DbSet<ClassA> ClassAs { get; set; }
public DbSet<ClassB> ClassBs { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Base>(entity =>
{
entity.HasKey(e => e.Id);
entity.HasDiscriminator(e => e.Type)
.HasValue<ClassA>(MyTypeEnum.A)
.HasValue<ClassB>(MyTypeEnum.B);
});
}
}
The migrations create the table as I expected and everything works like a charm, BUT (and here's my problem) I don't understand why ef fails to translate queries on the base class:
what I'm trying to do is querying the whole Base table to get all ClassA and ClassB entities and performs some operations on that, but ef core seems to fail while translating linq to SQL.
For example _context.Base.Count();
fetches ALL the Base
table in memory and then performs the count, instead of just translating to select count(*) from base
, and it fails in the same way when I try to use skip and take.
Is there a workaround?
linq
.net-core
entity-framework-core
ef-core-5.0
0 Answers
Your Answer