skip to content

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.