dotnet / efcore

EF Core is a modern object-database mapper for .NET. It supports LINQ queries, change tracking, updates, and schema migrations.
https://docs.microsoft.com/ef/
MIT License
13.79k stars 3.19k forks source link

How to use IncludeProperties on HasIndex for a mix of base and derived entities using TPH? #25813

Open joakimriedel opened 3 years ago

joakimriedel commented 3 years ago

I'm using TPH for a set of entities where columns of derived entities sometimes gets combined in a complex query. For this query, I need to add an index that includes these columns. I expected the following fluent API setup to work, but it doesn't.

modelBuilder.Entity<BaseEntity>()
    .HasDiscriminator(oa => oa.Kind)
    .HasValue<DerivedEntity1>(EntityKind.First)
    .HasValue<DerivedEntity2>(EntityKind.Second);
modelBuilder.Entity<BaseEntity>()
    .HasIndex(oa => new { oa.BaseProperty1, oa.BaseProperty2 })
    .IncludeProperties(oa => new { oa.BaseProperty3, (oa as DerivedEntity1).UniquePropertyForDerivedEntity1, (oa as DerivedEntity2).UniquePropertyForDerivedEntity2 });

But this fails with

The include property 'UniquePropertyForDerivedEntity1' specified on the index {'BaseProperty1', 'BaseProperty2 '} was not found on entity type 'BaseEntity'.

I've tried using string parameters instead of an expression, but get the same error.

How do I include additional columns from different derived entities into a single index without manually hacking the migration files?

Include provider and version information

EF Core version: 6 preview 5 Database provider: Microsoft.EntityFrameworkCore.SqlServer Target framework: .NET 5.0

ajcvickers commented 3 years ago

Related to #11336.

@joakimriedel This is currently not possible. The workaround is to modify the generated migration and explicitly add the filtered columns there.