Including derived child properties in Entity Framework Core 2.0

断了今生、忘了曾经 提交于 2019-12-01 17:57:31

问题


Using Entity Framework Core 2.0, I am trying to construct a query to include related data for a polymorphic child entity.

For example, given the following types:

    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; }

    }

and the following configuration:

    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);
    }

I am trying to write the following query:

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

Unfortunately, this is resulting in a syntax error.

However, I believe I am following the syntax as specified in https://github.com/aspnet/EntityFrameworkCore/commit/07afd7aa330da5b6d90d518da7375d8bbf676dfd

Can anyone suggest what I'm doing wrong?

Thanks


回答1:


This functionality is not available in EFC 2.0.

It's been tracked as #3910 Query: Support Include/ThenInclude for navigation on derived type and according to the current EFC Roadmap, it's scheduled for EFC 2.1 release (Include for derived types item under Features we have committed to complete).



来源:https://stackoverflow.com/questions/46077007/including-derived-child-properties-in-entity-framework-core-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!