How does EF Core map inheritance hierarchies to database tables, and what are the three main strategies (TPH, TPT, TPC)?
Short answer
Table-Per-Hierarchy (TPH, the default) stores all types in a single table with a discriminator column identifying each row's actual type -- simplest and most performant for queries, but can lead to many nullable columns.
Advertisement
AModel answer
Table-Per-Hierarchy (TPH, the default) stores all types in a single table with a discriminator column identifying each row's actual type -- simplest and most performant for queries, but can lead to many nullable columns. Table-Per-Type (TPT) creates a separate table per class in the hierarchy, joined via shared primary keys -- normalized but requires joins for queries. Table-Per-Concrete-Type (TPC) creates a fully independent table per concrete class with all inherited properties duplicated -- avoids joins entirely but duplicates schema and complicates cross-hierarchy queries.
public abstract class Animal { public int Id { get; set; } public string Name { get; set; } }
public class Dog : Animal { public string Breed { get; set; } }
public class Cat : Animal { public bool IsIndoor { get; set; } }
// TPH (default): one 'Animals' table with a 'Discriminator' column and nullable Breed/IsIndoor columns
modelBuilder.Entity<Animal>().HasDiscriminator<string>("AnimalType");Real-world example
A pet management system's Animal hierarchy uses the default TPH strategy for simplicity, accepting some nullable columns, since query performance (avoiding joins) matters more than schema normalization purity for this particular domain.
Likely follow-ups
- What are the trade-offs that would push you toward TPT or TPC instead of the TPH default?
- How does the discriminator column get automatically populated?
Related topics