EFCore Table Per Hierarchy: Query with base type in child element "Translation of member 'Parent' on entity type 'Base' failed"

21 hours ago 1
ARTICLE AD BOX

I don't believe this will work:

public class Parent { public int ID { get; set; } public List<D1> D1s { get; set; } public List<D2> D2s { get; set; } }

That will require 2 FK, one on D1 and one on D2 since the ParentID FK resides on Base, EF won't be able to resolve this down to either a D1 or D2 for the applicable collection.

Think of the mapping such as from the parent perspective:

.HasMany(p => p.D1s) .WithOne(d1 => d1.Parent) // Base.ParentId .HasMany(p => p.D2s) .WithOne(d2 => d2.Parent) // Base.ParentId Cannot have 2 mappings to same FK

EF won't allow two relationships to the same FK. Instead, we can have a single relationship mapped via the base type collection:

public class Parent { public int ID { get; set; } public List<Base> Children { get; private set; } = []; [NotMapped] public IEnumerable<D1> D1s => Children.OfType<D1>(); [NotMapped] public IEnumerable<D2> D2s => Children.OfType<D2>(); }

Where The relationship between parent and Base(s) is mapped, and the Bases (Children) need to be eager loaded to access D1s or D2s. Similarly, when querying parents by a D1 or D2, it needs to be done through parent => parent.Children To have the different collection references available you would be better off using TPC inheritance mapping.

Read Entire Article