EF core linq 在按层次结构基本类型查询表时无法转换为 SQL
我有 3 个这样的类(显然这是一个简化)
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; }
}
,我的数据库上下文是这样的
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);
});
}
}
迁移按照我的预期创建了表,一切都像魅力一样工作,但是(这是我的问题)我不明白为什么 ef 失败转换基类上的查询:
我想做的是查询整个基表以获取所有 ClassA 和 ClassB 实体并对其执行一些操作,但是 ef core 在将 linq 转换为 SQL 时似乎失败了。
例如 _context.Base.Count();
获取内存中的所有 Base
表,然后执行计数,而不是仅仅转换为 select count(*)来自base
,当我尝试使用skip和take时,它以同样的方式失败。
有解决方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论