skip to content

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%

answer

  1. configured on the root type only
  2. HasDiscriminator<string>("PaymentType")
  3. HasValue<CardPayment>("card")
  4. map it to an enum property instead
  5. IsComplete(false): filter every query

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.

solid answer

~40 s

The discriminator is configured on the root of the hierarchy. `modelBuilder.Entity<Payment>().HasDiscriminator<string>("PaymentType")` renames the shadow column and fixes its type, and `.HasValue<CardPayment>("card").HasValue<BankTransferPayment>("bank").HasValue<VoucherPayment>("voucher")` replaces the default class-name values, so renaming a C# class no longer changes stored data. `HasDiscriminator(p => p.Method)` maps it to a real property instead, for example a `PaymentMethod` enum. A relational convention sizes a string discriminator to fit the longest value. Normally a query on `db.Payments` has no discriminator filter, and a row whose value matches no mapped type makes materialization fail. `IsComplete(false)` tells EF Core the mapping is incomplete, so every query, base type included, gets `WHERE PaymentType IN ('card', 'bank', 'voucher')` and unknown rows are skipped.

code

csharp · 10 lines
csharp
modelBuilder.Entity<Payment>()
    .HasDiscriminator<string>("PaymentType")
    .HasValue<CardPayment>("card")
    .HasValue<BankTransferPayment>("bank")
    .HasValue<VoucherPayment>("voucher")
    .IsComplete(false);

modelBuilder.Entity<Payment>()
    .Property<string>("PaymentType")
    .HasMaxLength(16);

go deeper

for a junior

Recall that HasDiscriminator on the root type names the column and HasValue sets each subclass's stored value.

for a middle

Explain the default class-name values, why explicit values protect data from class renames, and how a property-mapped discriminator works.

for a senior

Know what IsComplete(false) adds to base queries, the length convention that alters the column as values grow, and the shared-column caveat.

for a principal

Set the rule that discriminator values are stable data contracts, owned like column names, before a hierarchy reaches production.

## Why configure the discriminator at all Under table-per-hierarchy (TPH) every payment shares one table, and a **discriminator** column says which class a row belongs to. EF Core's defaults are a shadow `string` column named `Discriminator` holding the class name, such as `CardPayment`. That default couples stored data to C# type names: rename `BankTransferPayment` to `TransferPayment` and existing rows no longer match any type. Teams therefore often choose short, stable values and a column name that fits their schema. ## Renaming the column and choosing values All discriminator configuration lives on the **root** entity type of the hierarchy: 1. `HasDiscriminator<string>("PaymentType")` names the shadow property and column and sets its CLR type. 2. `HasValue<CardPayment>("card")`, `HasValue<BankTransferPayment>("bank")` and `HasValue<VoucherPayment>("voucher")` set each type's value; the values must be unique within the hierarchy. 3. The shadow property can then be configured like any other, for example `Property<string>("PaymentType").HasMaxLength(16)`. EF Core still writes the value itself when a payment is added; your code never assigns it. ## Mapping the discriminator to a property Instead of a shadow property, the discriminator can be a real property on the base class: - `HasDiscriminator(p => p.Method)` with an `enum PaymentMethod { Card, BankTransfer, Voucher }`; - `.HasValue<CardPayment>(PaymentMethod.Card)` and so on for each type; - the enum is stored as a number by default; add `HasConversion<string>()` on the property to store names. The property is then visible to your code and to API projections, which is convenient for read models. Treat it as read-only: the class already says what kind of payment an object is, and EF Core configures the discriminator so that changing it on an already saved entity throws at `SaveChanges`. ## The length convention For a string discriminator, a relational EF Core convention sets the maximum length from the longest value: it picks the smallest number in the sequence 1, 2, 3, 5, 8, 13, 21 and so on that fits. With `card`, `bank` and `voucher` the longest value has 7 characters, so the column gets length 8. Adding a subclass whose value is longer later changes the length, and the next migration alters the column. ## What IsComplete(false) changes By default EF Core assumes the discriminator mapping is **complete**: every row in the table belongs to a mapped type. A query for the whole hierarchy, `db.Payments`, therefore has no discriminator filter at all. If a row holds a value no type is mapped to, for example rows written by another system, materialization fails with "No discriminators matched the discriminator value". `HasDiscriminator(...).IsComplete(false)` turns that assumption off: | Query | Complete (default) | `IsComplete(false)` | |---|---|---| | `db.Payments` | no filter | `WHERE PaymentType IN ('card', 'bank', 'voucher')` | | `db.Set<CardPayment>()` | `WHERE PaymentType = 'card'` | the same | | a row with an unknown value | materialization error | silently skipped | The trade is one extra predicate on base-type queries against tolerance of foreign rows. Prefer fixing the data; reach for `IsComplete(false)` when the table is genuinely shared with rows EF Core should ignore. ## Indexing and choosing values - Queries for one payment kind filter on the discriminator, so a large table benefits from an index on it: `HasIndex("PaymentType")` works on the shadow property by name. - Short, lowercase, stable values (`card`, `bank`, `voucher`) keep the column narrow and survive class renames and namespace moves. - Values are data: once rows exist, changing a value needs a data migration that rewrites those rows in the same release. ## Shared columns between siblings Sibling types sometimes have properties with the same meaning, such as a `Reference` on both `BankTransferPayment` and `VoucherPayment`. By default EF Core gives each its own column. If their types are identical, configuring both with the same `HasColumnName("Reference")` stores them in one column. One caveat from the EF Core documentation: a query that casts across siblings, such as reading `(p as BankTransferPayment).Reference`, also returns the shared column's values for voucher rows unless you add a type check. ## Checklist - Configure on the root with `HasDiscriminator`, never on a subclass. - Give every concrete type an explicit `HasValue` once data is in production. - Map to an enum property when code needs to read the type without a cast. - Use `IsComplete(false)` only for tables that hold rows outside the model.

  • Does IsComplete(false) change the SQL that db.Set<CardPayment>() sends?
    No. A query for a subtype already filters on that type's discriminator value, or values when it has subtypes of its own. `IsComplete(false)` adds the `IN` filter where EF Core would otherwise skip it, which in practice means queries on the root type, such as `db.Payments`.
  • Why can renaming a payment class break an application that never configured the discriminator?
    The default discriminator value is the CLR class name. After a rename, new rows get the new name while existing rows keep the old one, which no type maps to any more, so reading them fails. Explicit `HasValue` values decouple stored data from class names; with them, a rename is a code-only change.

  • HasDiscriminator can be configured separately on each subclass.
  • IsComplete(false) removes the discriminator column from the table.
  • With default settings, db.Payments filters on every known discriminator value.
  • Discriminator values are the integer positions of the subclasses.
  • Mapping the discriminator to a property means your code must set it before saving.