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
An Entity can include two types of properties: Scalar Properties and Navigation Properties. Scalar Property: The type of primitive property is called scalar properties. Each scalar property maps to a column in the database table which stores the real data.
You can then configure foreign key properties by using the HasForeignKey method. This method takes a lambda expression that represents the property to be used as the foreign key.
By default, EF maps the inheritance using the table-per-hierarchy (TPH) pattern. TPH uses a single table to store the data for all types in the hierarchy, and a discriminator column is used to identify which type each row represents.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With