EF core linq 在按层次结构基本类型查询表时无法转换为 SQL

发布于 01-15 18:16 字数 1302 浏览 4 评论 0原文

我有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文