Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 41 ยท Relationships and Loading

Inheritance Mapping (TPH, TPT, TPC)

Map C# class hierarchies to tables in EF Core: table-per-hierarchy with a discriminator, table-per-type and table-per-concrete-type, with trade-offs and runnable stand-ins.

C# has inheritance; relational databases do not. A Payment base class with CardPayment and BankTransfer subclasses is natural in code, but a database has only tables and rows. EF Core offers three strategies to bridge the gap, and choosing the right one affects query speed, storage and how clean your schema looks.

EF Core code is read-only on this site (there is no database provider here). The runnable blocks are labelled stand-ins that model the row layout each strategy produces, so you can see what ends up in the tables.

The example hierarchy

C#
public abstract class Payment
{
    public int Id { get; set; }
    public decimal Amount { get; set; }
    public DateTime PaidAt { get; set; }
}

public class CardPayment : Payment
{
    public string Last4 { get; set; } = "";
    public string Network { get; set; } = "";
}

public class BankTransfer : Payment
{
    public string Iban { get; set; } = "";
}

public class AppDbContext : DbContext
{
    public DbSet<Payment> Payments => Set<Payment>();
}

Only the base type needs a DbSet. If you add the subclasses to the model (a DbSet<CardPayment>, or modelBuilder.Entity<CardPayment>()), EF Core discovers the hierarchy. Queries on the base type return a mix of derived types, and OfType<CardPayment>() filters to one subtype.

Table-per-hierarchy (TPH), the default

TPH stores the whole hierarchy in one table. Columns of every subclass are added (nullable), and a discriminator column says which class each row represents.

SQL
CREATE TABLE Payments (
    Id            INT PRIMARY KEY,
    Amount        DECIMAL(18,2) NOT NULL,
    PaidAt        DATETIME2     NOT NULL,
    Discriminator NVARCHAR(21)  NOT NULL,   -- 'CardPayment' or 'BankTransfer'
    Last4         NVARCHAR(4)   NULL,       -- CardPayment only
    Network       NVARCHAR(MAX) NULL,       -- CardPayment only
    Iban          NVARCHAR(MAX) NULL        -- BankTransfer only
);

You can control the discriminator:

C#
modelBuilder.Entity<Payment>()
    .HasDiscriminator<string>("Kind")
    .HasValue<CardPayment>("card")
    .HasValue<BankTransfer>("bank");

Strengths: the fastest queries (no joins), a simple schema, and SELECT ... WHERE Discriminator IN (...) is cheap. Weaknesses: many nullable columns, you cannot declare subclass columns NOT NULL at the database level (EF Core enforces required-ness only in C#), and a wide table gets wider with every subclass.

C# Stand-in: a TPH table with a discriminator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Table-per-type (TPT)

TPT gives each class its own table. The base table holds shared columns; each derived table holds only its own columns, and its primary key is also a foreign key to the base table.

C#
modelBuilder.Entity<Payment>().UseTptMappingStrategy();
modelBuilder.Entity<CardPayment>().ToTable("CardPayments");
modelBuilder.Entity<BankTransfer>().ToTable("BankTransfers");
SQL
CREATE TABLE Payments      (Id INT PRIMARY KEY, Amount DECIMAL(18,2) NOT NULL, PaidAt DATETIME2 NOT NULL);
CREATE TABLE CardPayments  (Id INT PRIMARY KEY REFERENCES Payments(Id), Last4 NVARCHAR(4) NOT NULL, Network NVARCHAR(MAX) NOT NULL);
CREATE TABLE BankTransfers (Id INT PRIMARY KEY REFERENCES Payments(Id), Iban NVARCHAR(MAX) NOT NULL);

Strengths: a normalized schema with real NOT NULL constraints, and no wasted columns. Weaknesses: reading the base type LEFT JOINs every subtype table, which gets slower as the hierarchy grows, and inserting one object writes to two tables. In EF Core benchmarks TPT is usually noticeably slower than TPH for large tables, so choose it for data-model purity, not speed.

Table-per-concrete-type (TPC)

TPC (EF Core 7+) gives every concrete class a table that contains all its columns, including the inherited ones. The abstract base class gets no table.

C#
modelBuilder.Entity<Payment>().UseTpcMappingStrategy();
SQL
CREATE TABLE CardPayments  (Id INT PRIMARY KEY, Amount DECIMAL(18,2), PaidAt DATETIME2, Last4 NVARCHAR(4), Network NVARCHAR(MAX));
CREATE TABLE BankTransfers (Id INT PRIMARY KEY, Amount DECIMAL(18,2), PaidAt DATETIME2, Iban NVARCHAR(MAX));

Querying the base type becomes a UNION ALL over the concrete tables; querying one subtype hits just one table with no joins. Because the tables are independent, primary keys must not clash: you cannot rely on identity columns that each start at 1. Use GUIDs, a sequence shared across the tables (UseHiLo or a sequence default), or another scheme that is unique across the hierarchy. EF Core's SQL Server provider switches to a shared sequence by default for TPC keys.

Strengths: no nullable columns, no joins when you query one concrete type. Weaknesses: polymorphic queries UNION several tables, and foreign keys that point at the base type (a Refund that references any Payment) cannot be real database foreign keys, because no single table holds all payments.

C# Stand-in: the same data in three layouts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Choosing a strategy

TPH TPT TPC
Joins for subtype query none yes none
Polymorphic query single table joins UNION ALL
NOT NULL on subclass columns no yes yes
Default in EF Core yes no no
flowchart TD
    A["Do you query the base type often?"] -->|yes| B["Do subclasses add few columns?"]
    A -->|"no, mostly one subtype"| C["TPC"]
    B -->|yes| D["TPH (default)"]
    B -->|"no, and schema purity matters"| E["TPT"]

A rough decision flow. When in doubt, start with TPH and measure.

Things to watch

  • Do you really need inheritance? Often a Kind enum plus a few nullable columns, or composition (an owned type, see value converters and owned types), is simpler than a hierarchy.
  • Querying subtypes: db.Payments.OfType<CardPayment>() is translated to SQL; .Where(p => p is CardPayment c && c.Network == "visa") also works.
  • Relationships on subclasses work as usual (see one-to-many relationships). In TPH, a foreign key declared on a subclass becomes a nullable column on the shared table.
  • Shared columns: two subclasses can map different properties to the same column with HasColumnName if the types match, which reduces TPH width.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which inheritance strategy does EF Core use by default?

    TPH, one table with a discriminator column, is the default because it needs no joins and is the fastest.
  2. 2. What is the discriminator column for?

    In TPH every row has a value such as 'CardPayment' so EF Core knows which type to create.
  3. 3. What is the main drawback of TPT for large hierarchies?

    Reading the base type joins all subtype tables, and each insert writes to two tables.
  4. 4. Why must TPC keys be unique across the hierarchy?

    If two tables both hold Id 1, a polymorphic query would return two different entities with the same key. Use GUIDs or a shared sequence.

Summary

  • EF Core maps inheritance with TPH (default, one table), TPT (table per class) and TPC (table per concrete class).
  • TPH is fastest but has many nullable columns; TPT is normalized but join-heavy; TPC avoids joins for one subtype but needs hierarchy-unique keys.
  • OfType<T>() filters a hierarchy by subtype.
  • Consider composition or an enum before reaching for inheritance.

Next: How change tracking works