【问题标题】:Including derived child properties in Entity Framework Core 2.0在 Entity Framework Core 2.0 中包含派生的子属性
【发布时间】:2017-09-06 21:59:48
【问题描述】:

使用 Entity Framework Core 2.0,我正在尝试构建一个查询以包含多态子实体的相关数据。

例如,给定以下类型:

    public class ParentEntity
    {
        public int Id { get; set; }

        public IList<ChildEntityBase> Children { get; set; }
    }

    public abstract class ChildEntityBase
    {
        public int Id { get; set; }
    }

    public class ChildEntityA : ChildEntityBase
    {
    }

    public class ChildEntityB : ChildEntityBase
    {
        public IList<GrandchildEntity> Children { get; set; }
    }

    public class GrandchildEntity
    {
        public int Id { get; set; }

    }

还有如下配置:

    public DbSet<ParentEntity> ParentEntities { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<ParentEntity>().HasKey(p => p.Id);
        builder.Entity<ParentEntity>().HasMany(p => p.Children).WithOne();

        builder.Entity<ChildEntityBase>().HasKey(c => c.Id);
        builder.Entity<ChildEntityBase>()
            .HasDiscriminator<string>("ChildEntityType")
            .HasValue<ChildEntityA>("a")
            .HasValue<ChildEntityB>("b");

        builder.Entity<ChildEntityA>()
            .HasBaseType<ChildEntityBase>();

        builder.Entity<ChildEntityB>()
            .HasBaseType<ChildEntityBase>()
            .HasMany(u => u.Children).WithOne();

        builder.Entity<GrandchildEntity>()
            .HasBaseType<ChildEntityBase>();

        base.OnModelCreating(builder);
    }

我正在尝试编写以下查询:

        var result = this.serviceDbContext.ParentEntities
            .Include(p => p.Children)
            .ThenInclude((ChildEntityB b) => b.Children);

很遗憾,这会导致语法错误。

但是,我相信我遵循https://github.com/aspnet/EntityFrameworkCore/commit/07afd7aa330da5b6d90d518da7375d8bbf676dfd 中指定的语法

谁能建议我做错了什么?

谢谢

【问题讨论】:

    标签: entity-framework-core


    【解决方案1】:

    此功能在 EFC 2.0 中不可用。

    它被跟踪为 #3910 Query: Support Include/ThenInclude for navigation on derived type,根据当前的 EFC Roadmap,它计划在 EFC 2.1 版本中发布(包含用于派生类型项目在 Features we have committed to complete 下)。

    【讨论】:

    • 这就解释了。对于多态子类型,我可以使用 ThenInclude 的替代方法吗?
    • 不,这就是问题所在 :( 在他们提供之前,您必须手动进行(基本上使用显式加载) - 就像 here。但是没有不实现查询的解决方法。
    • 谢谢伊万。很有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多