EF Core TPH Inheritance — Complete Guide
In this tutorial, you'll learn about EF Core TPH Inheritance. We cover key concepts, practical examples, and best practices.
You have a base Animal class with subclasses Dog and Cat. TPH stores all types in a single table with a discriminator column that identifies which type each row represents. This is the default inheritance mapping in EF Core.
Default
public class Animal
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Dog : Animal
{
public string Breed { get; set; }
public bool IsGoodBoy { get; set; }
}
public class Cat : Animal
{
public bool IsIndoor { get; set; }
}
Output: Single Animals table with columns: Id, Name, Discriminator, Breed, IsGoodBoy, IsIndoor. The Discriminator column stores "Animal", "Dog", or "Cat".
Configure discriminator:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Animal>()
.HasDiscriminator<string>("Type")
.HasValue<Animal>("animal")
.HasValue<Dog>("dog")
.HasValue<Cat>("cat");
}
Prevention
- Use TPH by default — it is the simplest and most performant strategy.
- Use TPH when subclasses have few unique properties.
- Use TPH when you frequently query the base type across all subtypes.
- Use TPC or TPT when subclasses have many unique non-nullable columns.
- Configure the discriminator column name and values explicitly for clarity.
- Add indexes on the discriminator column for filtered queries.
- Use
[Discriminator]attribute for simple configuration.
Common Mistakes with core tph inheritance
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world EF code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
TPH is the standard inheritance strategy in DodaTech's content management system. For more EF Core, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro