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?
answer
- keys unique across the whole hierarchy
- no shared table to own the counter
- default: one PaymentSequence for all tables
- HiLo, seeded identities or Guid keys
- TpcStoreGeneratedIdentityWarning
basics
~20 sEF 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.
solid answer
~40 sEF Core identifies an entity by its key across the entire hierarchy: a `CardPayment` with `Id` 7 and a `VoucherPayment` with `Id` 7 would be the same `Payment` to the change tracker. Under TPH and TPT one table owns every key, so an identity column works. Under TPC there is no such table, and per-table identity columns would each count from 1. Both the SQL Server provider and Npgsql switch an integer TPC key from their identity default to a **sequence**: EF Core creates `PaymentSequence` (root type name plus `Sequence`) and every table's key column takes its default from it. Alternatives: a HiLo sequence (`UseHiLo`), per-table identities with disjoint seeds and increments (hard to extend when a payment type is added), or client-generated `Guid` keys. Forcing an incompatible store-generated key logs `TpcStoreGeneratedIdentityWarning`.
code
csharp · 6 linesmodelBuilder.Entity<Payment>().UseTpcMappingStrategy();
// optional: the default is a sequence named PaymentSequence
modelBuilder.Entity<Payment>()
.Property(p => p.Id)
.UseSequence("payment_ids");go deeper
Recall that TPC tables cannot each count ids from 1, and that EF Core uses one shared sequence instead.
Explain why keys must be unique across the hierarchy and how the PaymentSequence default reaches every table.
Compare the sequence, HiLo, seeded identities and Guid keys, and plan the sequence's start value when converting a populated hierarchy to TPC.
Weigh TPC's key and integrity costs - a shared sequence, no foreign key constraints - against its query gains before standardising on it.
## Keys must be unique across the hierarchy In EF Core, an entity's key identifies it within its **whole inheritance hierarchy**, not just within its own CLR type. The change tracker keys its identity map by the root type, and `db.Payments.FindAsync(7)` must return exactly one payment, whatever its subclass. So a `CardPayment` and a `VoucherPayment` may never share a key value. How the strategies meet that rule: - **TPH**: one table holds every payment, so any key generation works, typically an identity column (Npgsql's default is an identity column; SQL Server's is `IDENTITY`). - **TPT**: every payment has a row in the base `Payments` table, which generates the key; subtype tables reuse it through their foreign key. - **TPC**: each concrete type has its own table, and nothing is shared. An identity column in `CardPayments` and another in `VoucherPayments` would both start at 1, and the second payment of each kind would collide in the change tracker. ## The default: one shared sequence A database **sequence** is a counter object that lives outside any table, so several tables can draw from it. That makes it the natural TPC key source, and the providers switch to it automatically: 1. The SQL Server provider and Npgsql both check whether the key's declaring type uses the TPC strategy; if it does, an integer key that would have been an identity column uses the `Sequence` strategy instead. 2. EF Core creates one sequence per hierarchy, named after the root type with the suffix `Sequence`, so `PaymentSequence`. 3. Each table's key column gets a default that takes the next value from it: `NEXT VALUE FOR [PaymentSequence]` on SQL Server, a `nextval(...)` call on PostgreSQL. 4. Inserts still let the database generate the value, and EF Core reads it back as it would from an identity column. The sequence name can be changed by configuring the key with `UseSequence("payment_ids")` on the root type's key property. ## Alternatives and their costs | Approach | How | Watch out for | |---|---|---| | Shared sequence (default) | nothing to configure | one extra database object per hierarchy | | HiLo | `UseHiLo()` on the key | EF Core reserves blocks of values, so ids have gaps and are not in insert order | | Per-table identities with disjoint seeds | `UseIdentityColumn(1, 3)`, `UseIdentityColumn(2, 3)`, `UseIdentityColumn(3, 3)` per table on SQL Server | the increment fixes the number of types; adding a fourth payment kind means re-seeding | | Client-generated `Guid` keys | a `Guid` key, generated by EF Core when the entity is added | wider keys and indexes; works on every database | Two more facts complete the picture: - **SQLite has neither sequences nor identity seeds and increments**, so integer key generation is not supported there with TPC; use `Guid` keys or generate values in code. - If the key is configured with a store-generated default that cannot work across TPC tables, model validation logs **`RelationalEventId.TpcStoreGeneratedIdentityWarning`**, telling you to choose a compatible strategy or non-generated keys. ## Choosing among them - Keep the **default sequence** unless there is a reason not to: no configuration, database-generated, ordered ids. - Use **HiLo** when insert throughput matters and many new payments are added per `SaveChanges`, since EF Core assigns keys from a reserved block without a round trip per row. - Use **`Guid` keys** when ids are created outside the database, for example by an API before the payment is stored, or when SQLite must be supported. - Avoid **seeded identities** for any hierarchy that is still growing. ## Related consequence: references into the hierarchy Because no single table holds every payment key, a foreign key from another table, such as `Refund.PaymentId`, cannot be backed by a database constraint under TPC. The shared sequence still guarantees that a `PaymentId` value points at no more than one payment, but the database does not check that it points at any. ## Where it shows up in a migration Switching an existing hierarchy to TPC creates the sequence, adds key defaults to each concrete table and removes identity from them. Read the generated migration, and if the tables already contain data, set the sequence's starting value above the highest existing key before the first insert, or new ids will clash with old ones.
- Why is a seeded identity per table (1 and 3, 2 and 3, 3 and 3) a fragile alternative?The increment encodes the number of concrete types. With increment 3, three tables never collide, but a fourth payment kind needs a free residue that does not exist, so every table must be re-seeded with a new increment. The shared sequence needs no change when a type is added.
- Why does EF Core care that a CardPayment and a VoucherPayment never share an Id when they live in different tables?EF Core treats them as one entity set: the change tracker indexes tracked entities by the root type's key, and `Find` or a reference to `Payment` resolves by key alone. Two payments with the same key would be an identity conflict, so keys must be unique across the hierarchy regardless of the tables.
A shared sequence is the ticket roll at a deli with several counters: every counter tears its number from the same roll, so no two customers anywhere in the shop hold the same number. Giving each counter its own roll starting at 1 is the per-table identity column, and the duplicates appear on the second customer.
- Each TPC table can keep its own identity column starting at 1.
- EF Core only needs keys to be unique within each CLR type.
- TPC forces Guid keys on every provider.
- Npgsql uses an identity column for a TPC key just as it does under TPH.
- SQLite supports integer key generation for TPC through AUTOINCREMENT.