skip to content

In EF Core 10, how do you map a strongly typed OrderId record struct as a primary and foreign key, and what stops working?

level: seniorimportance: should knowfreq 42%

answer

  1. the database still stores an int
  2. ValueConverter<OrderId, int>
  3. ConfigureConventions: Properties<OrderId>().HaveConversion
  4. ValueGeneratedOnAdd is not inferred
  5. o.Id.Value does not translate

basics

~20 s

Give OrderId a ValueConverter<OrderId, int>, ideally once in ConfigureConventions so the key and every foreign key share it, and call ValueGeneratedOnAdd if the database should generate ids. Queries must compare whole OrderId values; members such as o.Id.Value do not translate.

solid answer

~40 s

A strongly typed id such as `readonly record struct OrderId(int Value)` is mapped through a value converter to the column's type. Registering it in `ConfigureConventions` with `configurationBuilder.Properties<OrderId>().HaveConversion<OrderIdConverter>()` covers `Order.Id` and every `OrderLine.OrderId` foreign key at once. EF Core's value-generation convention only switches on for integer (except `byte`) and `Guid` CLR types, so it does not see `OrderId` as generatable: call `Property(o => o.Id).ValueGeneratedOnAdd()` (supported for converted keys since EF Core 7) and the provider creates an identity column. In LINQ, compare whole values, `o.Id == orderId`, which EF Core converts to an `int` parameter; `o.Id.Value == 42` cannot be translated. Pass the raw `int` to `FromSql`, and pass an `OrderId`, not an `int`, to `FindAsync`.

code

csharp · 19 lines
csharp
public readonly record struct OrderId(int Value);

public sealed class OrderIdConverter : ValueConverter<OrderId, int>
{
    public OrderIdConverter()
        : base(id => id.Value, value => new OrderId(value)) { }
}

public class ShopContext(DbContextOptions<ShopContext> options) : DbContext(options)
{
    public DbSet<Order> Orders => Set<Order>();
    public DbSet<OrderLine> OrderLines => Set<OrderLine>();

    protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
        => configurationBuilder.Properties<OrderId>().HaveConversion<OrderIdConverter>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
        => modelBuilder.Entity<Order>().Property(o => o.Id).ValueGeneratedOnAdd();
}

go deeper

for a junior

Recall that the column still holds an int and that a ValueConverter translates between OrderId and int in both directions.

for a middle

Explain ConfigureConventions with HaveConversion, why it covers foreign keys, and why a struct id needs no extra equality work.

for a senior

Show the traps: ValueGeneratedOnAdd must be explicit, .Value does not translate, raw SQL and FindAsync want the right type, and the web edge needs binders and serializers.

for a principal

Decide whether strongly typed ids pay for themselves in this codebase, given the converters, binders and serializers every id type adds.

## Why teams wrap their keys A **strongly typed id** wraps a primitive key in a type of its own, such as `OrderId` around an `int` or `CustomerId` around a `Guid`. The compiler then refuses `LoadOrder(customer.Id)`, and a method signature says which id it wants. In a furniture shop with orders, order lines, products and customers all keyed by `int`, it removes a whole class of mix-ups. The EF Core documentation shows the pattern but also warns that it adds code and complexity, so it is a design choice rather than a default. ## The converter The database still stores a plain `int`, so EF Core needs a **value converter** between the model type and the provider type: `ValueConverter<OrderId, int>` with one expression for each direction. Two places can attach it: 1. Per property: `Property(o => o.Id).HasConversion(id => id.Value, v => new OrderId(v))`. The EF Core documentation's sample repeats the call on each foreign key property, which is easy to forget. 2. Model-wide, in `ConfigureConventions`: `configurationBuilder.Properties<OrderId>().HaveConversion<OrderIdConverter>()`. Every property of that CLR type, keys and foreign keys alike, picks the converter up, so this is the usual choice. Use a `struct` (a `readonly record struct` is ideal): it has value equality and EF Core compares structs memberwise. A class id needs overridden equality or a `ValueComparer`, otherwise two instances holding 42 are treated as different keys. ## Key generation is not inferred EF Core's value-generation convention marks a single-property key as generated only when its CLR type is an integer type (other than `byte`) or a `Guid`. `OrderId` is neither, so with a converter alone EF Core sends whatever the property holds, usually `OrderId(0)`, and the second new order collides. Since EF Core 7, converted keys can use database generation when the provider type supports it; you ask for it explicitly: - `modelBuilder.Entity<Order>().Property(o => o.Id).ValueGeneratedOnAdd();` - On SQL Server this becomes an `IDENTITY` column. - Npgsql checks the converter's provider type (`int`) and applies its default identity strategy, so the column becomes an identity column. ## What stops working, and what to write instead | You write | Result | |---|---| | `Where(o => o.Id == orderId)` | works; the `OrderId` parameter is converted to an `int` | | `Where(o => o.Id.Value == 42)` | fails: EF Core cannot query into a member of a value-converted type | | `FindAsync(42)` | throws: the key value type `int` does not match the property type `OrderId` | | `FindAsync(new OrderId(42))` | works | | `FromSql($"... WHERE "Id" = {orderId}")` | not supported: value-converted parameter types cannot be used in raw SQL | | `FromSql($"... WHERE "Id" = {orderId.Value}")` | works | Two more facts belong in the answer: - **Null never reaches a converter.** A nullable `OrderId?` foreign key maps to a nullable column; EF Core handles the null itself. - **The converter cannot see the context.** It is a pure function of the value, built from expressions that EF Core compiles into its materializer. ## The web edge An `OrderId` in a route or a JSON body is an ASP.NET Core binding concern, not an EF Core one: Minimal APIs need a `TryParse` method on the type to bind it from a route, and System.Text.Json needs a converter to read it from a body. Teams that adopt strongly typed ids usually generate those pieces, together with the EF Core converter, from one declaration. ## A checklist for each id type 1. Declare it as a `readonly record struct` wrapping the provider type. 2. Write one `ValueConverter` class with a parameterless constructor. 3. Register it in `ConfigureConventions` with `Properties<TId>().HaveConversion<TConverter>()`. 4. Call `ValueGeneratedOnAdd()` on keys the database generates, or create the value in code (typical for `Guid`-backed ids). 5. Add the web pieces: a `TryParse` for route binding and a JSON converter for bodies. ## Judging the trade - **Worth it** when many entities share one primitive key type and the domain code passes ids around a lot. - **Costly** in raw SQL, in dynamic queries that touch `.Value`, and in every serializer and binder at the edges. - **Keep it consistent**: one converter registered in `ConfigureConventions` per id type, and `ValueGeneratedOnAdd` wherever the database creates the value.

  • Why does Where(o => o.Id.Value == 42) fail when Where(o => o.Id == new OrderId(42)) works?
    EF Core knows how to convert a whole `OrderId` to its `int` column, so a comparison of two `OrderId` values becomes a comparison of the column with a converted parameter. It does not look inside the converter to learn that `.Value` corresponds to the column, so member access on a value-converted type has no SQL translation and the query throws.
  • Would you use a Guid-backed CustomerId instead, and what changes?
    The pattern is the same: a `ValueConverter<CustomerId, Guid>` registered in `ConfigureConventions`. The difference is who creates the value: with a `Guid` the application can create the id before saving, so the aggregate has its id immediately and no database round trip is needed. The converted key is not generated by convention anyway; `ValueGeneratedNever()` makes that explicit.

  • EF Core marks an OrderId key as database-generated by convention because it wraps an int.
  • A struct-based OrderId needs a custom ValueComparer because EF Core cannot compare structs.
  • Where(o => o.Id.Value == 42) translates because EF Core inlines the converter into SQL.
  • A class-based OrderId needs no equality override because EF Core compares keys by reference safely.
  • Value converters receive null for a nullable foreign key and must handle it.

Assumes EF Core 10; database-generated values for keys mapped through value converters have been supported since EF Core 7.