skip to content

TPH, TPT & TPC Mapping

Mapping a class hierarchy to tables: TPH with a discriminator by default, TPT with a table per type, or TPC per concrete class. Interviewers want the SQL each strategy emits and when it hurts.

part ofEntity Framework Coreread it →
on this pageshow

explore

questions

5

In EF Core 10, how does an abstract Payment class with CardPayment, BankTransferPayment and VoucherPayment subclasses map to tables by default?

level: juniorimportance: must knowfreq 50%

answer

  1. one table for the whole hierarchy
  2. table-per-hierarchy (TPH) is the default
  3. shadow Discriminator column, class names
  4. subclass columns become nullable
  5. subclasses must be in the model

basics

~20 s

By default EF Core uses table-per-hierarchy (TPH): every payment type goes into one Payments table, with a shadow Discriminator column holding the class name, such as CardPayment, and nullable columns for each subclass's properties. Subclasses must be added to the model explicitly.

solid answer

~40 s

EF Core maps a hierarchy with **table-per-hierarchy** unless told otherwise. One table, named after the `DbSet<Payment>` (`Payments`), holds every row; base properties are ordinary columns, and each subclass adds its own columns, which EF Core makes nullable because other payment types leave them empty. A shadow `Discriminator` string column records the type: by default the CLR class name, `CardPayment`, `BankTransferPayment` or `VoucherPayment`, and EF Core fills it on insert. EF Core does not scan for subclasses, so each must be in the model through a `DbSet<CardPayment>` or `modelBuilder.Entity<CardPayment>()`. Querying `db.Payments` returns `CardPayment`, `BankTransferPayment` and `VoucherPayment` instances from one `SELECT` with no filter; `db.Set<CardPayment>()` adds `WHERE Discriminator = 'CardPayment'`.

code

csharp · 22 lines
csharp
public abstract class Payment
{
    public int Id { get; set; }
    public decimal Amount { get; set; }
    public DateTime CreatedAt { get; set; }
}

public class CardPayment : Payment
{
    public required string CardBrand { get; set; }
    public required string CardLast4 { get; set; }
}
public class BankTransferPayment : Payment { public required string Iban { get; set; } }
public class VoucherPayment : Payment { public required string VoucherCode { get; set; } }

public class BillingContext(DbContextOptions<BillingContext> options) : DbContext(options)
{
    public DbSet<Payment> Payments => Set<Payment>();
    public DbSet<CardPayment> CardPayments => Set<CardPayment>();
    public DbSet<BankTransferPayment> BankTransfers => Set<BankTransferPayment>();
    public DbSet<VoucherPayment> VoucherPayments => Set<VoucherPayment>();
}

go deeper

for a junior

Recall TPH as the default: one table, a shadow Discriminator column holding class names, and subclasses registered with a DbSet or Entity<T>().

for a middle

Explain why subclass columns are nullable, how EF Core picks the class to create from the discriminator, and the filter a derived-type query adds.

for a senior

Point out what TPH costs - wide tables, NOT NULL rules the database can no longer enforce - and when that justifies a different strategy.

for a principal

Judge whether a hierarchy belongs in the database at all, given how TPH spreads business rules between the model and the schema.

## The default: table-per-hierarchy When some entity types derive from others, EF Core has to decide how the class hierarchy becomes tables. It supports three **mapping strategies**: table-per-hierarchy (TPH), table-per-type (TPT) and table-per-concrete-type (TPC). With no configuration it uses **TPH**, and since EF Core 7 you can also say so explicitly with `UseTphMappingStrategy()` on the root type. Take a billing model with an abstract `Payment` (`Id`, `Amount`, `CreatedAt`) and three subclasses: `CardPayment` (`CardBrand`, `CardLast4`), `BankTransferPayment` (`Iban`) and `VoucherPayment` (`VoucherCode`). Under TPH: 1. There is **one table**, named after the `DbSet<Payment>` property, here `Payments`. 2. It has a column for every property of every type in the hierarchy: `Id`, `Amount`, `CreatedAt`, `CardBrand`, `CardLast4`, `Iban`, `VoucherCode`. 3. It has an extra **discriminator** column, `Discriminator`, that says which class each row is. ## The Discriminator column EF Core adds the discriminator as a **shadow property**: it exists in the model and the table, but not on your classes. Its defaults: - the column is named `Discriminator`; - its type is `string`; - each type's value is its CLR class name without the namespace, so `CardPayment`, `BankTransferPayment` and `VoucherPayment`; - EF Core writes the value itself when a new entity is inserted, and reads it to decide which class to create for each row; - a relational convention gives the column a maximum length: the smallest number in the sequence 1, 2, 3, 5, 8, 13, 21 and so on that fits the longest value, so 21 here for the 19-character `BankTransferPayment`. An abstract class such as `Payment` never has rows of its own, because C# cannot create an instance of it. ## Nullable subclass columns Every row has every column, but a voucher payment has no card brand. EF Core therefore makes the columns of subclass properties **nullable** in the database, even when the C# property is non-nullable or `required`. `CardPayment.CardLast4` is required in your code, yet the `CardLast4` column accepts `NULL`, because voucher and bank-transfer rows need it to. The database can no longer guarantee that every card payment has a card number; your C# types and validation have to. ## Subclasses are not discovered for you EF Core does not scan an assembly for types derived from a mapped class. A subclass becomes part of the hierarchy only when the model mentions it: - a `DbSet<CardPayment>` property on the context, or - `modelBuilder.Entity<CardPayment>()` in `OnModelCreating`. A subclass that is never mentioned is simply not mapped, and saving an instance of it fails because EF Core does not know the type. ## What queries look like | LINQ | SQL shape under TPH | |---|---| | `db.Payments.ToListAsync()` | one `SELECT` from `Payments`, no filter; each row becomes its concrete class | | `db.Set<CardPayment>().ToListAsync()` | the same table, `WHERE Discriminator = 'CardPayment'` | | `db.Payments.OfType<CardPayment>()` | the same filter as the line above | That single table is why TPH is the default: reading payments of every kind needs no join and no union, and a derived-type query is one indexed filter away. The costs are the nullable columns and a wide table when the subclasses have many properties of their own. ## Saving and reading back - `db.Payments.Add(new VoucherPayment { ... })` inserts one row into `Payments` with `Discriminator = 'VoucherPayment'` and `NULL` in the card and bank columns. - Reading `db.Payments` creates a `VoucherPayment` object for that row, so ordinary C# type tests such as `payment is VoucherPayment` work on the results. - A saved payment cannot change kind by editing data: EF Core configures the discriminator so that modifying it on an existing entity throws at `SaveChanges`. Turning a voucher payment into a card payment means removing one entity and adding another. ## In an interview Name the strategy (TPH), the shadow `Discriminator` column and its class-name values, the nullable subclass columns, and the fact that subclasses must be registered. Then say that TPT and TPC exist and are chosen per hierarchy with `UseTptMappingStrategy()` or `UseTpcMappingStrategy()` on the root type.

  • Why is the CardLast4 column nullable when the C# property is required?
    Under TPH every payment shares one table, and bank-transfer and voucher rows have no card number. The database column must accept `NULL` for them, so EF Core creates subclass columns as nullable regardless of the C# nullability. The database therefore cannot enforce the rule for card rows; the C# `required` modifier and your validation have to.
  • What value does EF Core store in the Discriminator column for a new VoucherPayment, and who sets it?
    By default the class name without namespace, `VoucherPayment`. EF Core sets it when the entity is added and saved; your code never assigns the shadow property. Custom values come from `HasDiscriminator(...).HasValue<VoucherPayment>(...)` on the root type.

  • EF Core creates one table per class in the hierarchy unless configured otherwise.
  • EF Core finds every subclass of a mapped entity type automatically.
  • The Discriminator column stores the assembly-qualified type name.
  • A required property on a subclass becomes a NOT NULL column under TPH.
  • You must set the discriminator value yourself before calling SaveChanges.
open as a page

In EF Core 10, what SQL do db.Payments and db.Payments.OfType<CardPayment>() send under TPH, TPT and TPC, and which strategy suits which query pattern?

level: seniorimportance: must knowfreq 45%

basics

~20 s

TPH reads one table, adding a discriminator filter for OfType<CardPayment>(). TPT joins the base table to every subtype table and computes the type with CASE. TPC unions every concrete table, and OfType narrows that to the CardPayments table. TPH suits mixed-type reads; TPC suits single-type reads.

open as a page

In EF Core 10, how do you rename and re-value a TPH discriminator with HasDiscriminator and HasValue, and what does IsComplete(false) change?

level: middleimportance: should knowfreq 40%

basics

~20 s

Call HasDiscriminator<string>("PaymentType") on the root entity and chain HasValue<CardPayment>("card") for each type, or point HasDiscriminator at a CLR property such as an enum. IsComplete(false) makes EF Core filter even base-type queries to the known values.

open as a page

In EF Core 10, what tables do UseTptMappingStrategy and UseTpcMappingStrategy create for a Payment hierarchy, and how do the schemas differ?

level: middleimportance: should knowfreq 42%

basics

~20 s

Both are called on the root entity. TPT creates a Payments table for base columns plus a table per subclass whose key is also a foreign key to Payments. TPC creates one complete table per concrete class, repeating the base columns, and none for an abstract Payment.

open as a page

In EF Core 10, why can't a TPC payment hierarchy use an ordinary identity column per table, and how does EF Core generate its keys instead?

level: seniorimportance: should knowfreq 30%

basics

~20 s

EF Core requires keys unique across a whole hierarchy, but under TPC each concrete type has its own table, so separate identity columns would each start at 1 and collide. SQL Server and Npgsql therefore default integer TPC keys to one shared database sequence, such as PaymentSequence.

open as a page