skip to content

In EF Core 10, when do you map a value object such as an Address with ComplexProperty rather than OwnsOne, and what behaves differently?

level: middleimportance: must knowfreq 58%

answer

  1. identity versus value semantics
  2. owned type: hidden shadow key
  3. one instance on two properties
  4. ComplexProperty or [ComplexType], no navigations
  5. EF Core 10: structs, optional, JSON

basics

~20 s

Use ComplexProperty for a keyless value object such as an Address or a Money amount: complex types have value semantics, no hidden key and may be structs. Keep OwnsOne or OwnsMany for what complex types cannot do: a separate table or a navigation to an entity.

solid answer

~50 s

Both put a reference value in the owner's table by default, with columns such as `ShippingAddress_City`. An owned type is an entity behind the scenes: EF Core gives it a shadow key equal to the owner's key and tracks it by identity, so `customer.BillingAddress = customer.ShippingAddress` fails at `SaveChanges`, and comparing two owned values in LINQ compares identities. A complex type has no key at all: assignment copies the values, `==` in a query compares every column, it can be a `record` or (since EF Core 10) a `struct`, and EF Core 10 also lets it be optional, map to JSON and be set with `ExecuteUpdate`. Neither is discovered by convention: use `[ComplexType]` or `ComplexProperty`. Owned types still win when the value must live in its own table, hold a navigation to another entity, or be a collection stored as rows.

code

csharp · 22 lines
csharp
public record Address(string Street, string City, string PostCode, string Country);
public record Money(decimal Amount, string Currency);

public class Customer
{
    public int Id { get; set; }
    public required string Name { get; set; }
    public required Address ShippingAddress { get; set; }
    public Address? BillingAddress { get; set; }   // optional: EF Core 10
    public required Money CreditLimit { get; set; }
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Customer>(b =>
    {
        b.ComplexProperty(c => c.ShippingAddress);
        b.ComplexProperty(c => c.BillingAddress);
        b.ComplexProperty(c => c.CreditLimit,
            m => m.Property(x => x.Amount).HasPrecision(18, 2));
    });
}

go deeper

for a junior

Recall the two APIs, OwnsOne and ComplexProperty, and that an Address mapped either way becomes extra columns such as ShippingAddress_City in the owner's table.

for a middle

Explain the hidden shadow key that makes owned types entities, and show how it breaks shared assignment and LINQ equality where complex types copy and compare by value.

for a senior

Name the cases where OwnsOne still wins - its own table, navigations, row-based collections - and what EF Core 10 added to complex types before you recommend a switch.

for a principal

Weigh moving an established owned-type model to complex types: column renames, migration review and query behaviour changes against the bugs value semantics remove.

## Three kinds of things EF Core maps EF Core sorts the objects in a model into three groups: - **Primitive values** such as `int`, `string`, `Guid` or `DateOnly`: one property, one column. - **Entity types** such as `Customer` or `Order`: a key gives each instance an identity, and the change tracker follows that identity. - **Value objects** such as an `Address` or a `Money` amount: several values grouped together with no identity of their own. Two addresses with the same street, city and post code are simply equal. EF Core offers two ways to map the third group: **owned entity types** (`OwnsOne`, `OwnsMany`, `[Owned]`) and **complex types** (`ComplexProperty`, `ComplexCollection`, `[ComplexType]`). Complex types arrived in EF Core 8 and were extended substantially in EF Core 10, and the EF Core documentation now points value objects at them. ## Owned types are entities in disguise An owned type looks keyless in C#, but EF Core models it as an entity type on the dependent side of a relationship with its owner. For `OwnsOne` it creates a **shadow primary key** whose value equals the owner's key; for `OwnsMany` the default key is the owner's foreign key plus a generated `Id`. Because there is a key, the change tracker follows each owned instance by identity, and that leaks into behaviour: - the same `Address` instance cannot back two navigations, so `customer.BillingAddress = customer.ShippingAddress` fails when `SaveChanges` runs; - comparing two owned values in a LINQ query compares identities, not contents; - `ExecuteUpdate` cannot set owned properties; - the CLR type must be a reference type. ## Complex types have value semantics A complex type has no key, hidden or otherwise. It cannot have a `DbSet<T>`, cannot be queried or tracked on its own, and is stored inside its owner's row, either as extra columns (**table splitting**) or as one JSON column. In exchange it behaves like a value: 1. Assigning one complex value to another property copies the values. EF Core still tracks each scalar inside it, so the `UPDATE` touches only the columns that changed. 2. `Where(c => c.ShippingAddress == c.BillingAddress)` compares every column of the two addresses. 3. The type may be a class, a `record` or, since EF Core 10, a `struct` (collections of structs are not supported yet). 4. Since EF Core 10 a complex property can be optional (`Address?`), can be mapped to JSON with `ToJson()`, can be a collection (JSON only), and can be set in bulk with `ExecuteUpdate`. | Aspect | Owned entity type | Complex type | |---|---|---| | Identity | hidden shadow key | none; compared by value | | Same instance on two properties | fails | works, values are copied | | CLR type | class only | class, record or struct | | Storage | owner's table, its own table, or JSON | owner's table or JSON only | | Navigations to entities | allowed | not allowed | | Collections | `OwnsMany`: own table or JSON | `ComplexCollection`: JSON only | | `ExecuteUpdate` | not supported | supported | ## Declaring a complex type On relational providers neither kind is discovered by convention. Leave an `Address` property unconfigured and EF Core treats `Address` as an ordinary entity type, then fails model validation because it "requires a primary key to be defined". Mark the class with `[ComplexType]` or call `ComplexProperty` in `OnModelCreating`; the nested builder configures facets such as `HasPrecision` on a `Money.Amount` or `HasColumnName` on a street. Columns are named after the path: `ShippingAddress_Street`, `ShippingAddress_City`, and for a nested complex type the full path, such as `Contact_HomePhone_Number`. An optional complex property needs at least one **required** property inside the type, because EF Core uses a non-nullable column to tell a null `Address` from an `Address` whose values all happen to be null. ## When owned types still win - The value must live in its **own table** (`OwnsOne(...).ToTable(...)`), or a collection must be stored as rows rather than as a JSON array (`OwnsMany`). - The value holds a **navigation** to another entity, for example a delivery booking that points at a `Warehouse` entity. - An existing model already uses owned types and none of the problems above bites yet. The EF Core documentation encourages moving to complex types, but the switch changes the model and should be planned with a migration review. One more test comes before either choice: if several entities must see the same address change together, it is not a value object. Model it as an entity with its own key and reference it through a navigation. ## In an interview State the identity difference first, prove it with the shared-address assignment, then name what EF Core 10 added to complex types. That shows you know both the model and the release.

  • What does customer.BillingAddress = customer.ShippingAddress do with OwnsOne compared with ComplexProperty?
    With `OwnsOne` the address instance is an entity with a key tied to one navigation, so pointing a second navigation at the same instance fails when `SaveChanges` runs; you must create a new `Address`. With `ComplexProperty` the values are copied, and EF Core issues an `UPDATE` for the billing columns whose values changed.
  • What did EF Core 10 change about complex-type column names?
    Two properties whose columns would collide are no longer silently mapped to one column; EF Core 10 appends a number to make the name unique. Nested complex properties now use the full path, `Complex_NestedComplex_Property` instead of `NestedComplex_Property`. To share a column on purpose, or keep an old name, set `HasColumnName` through the complex property's `Property` builder.

  • Owned types and complex types are two names for the same mapping.
  • A complex type gets its own table with a foreign key back to the owner.
  • EF Core discovers an Address class as a complex type by convention.
  • Edits inside a complex type are never saved because complex types are not tracked.
  • One owned Address instance can back two navigations because owned types have no key.

Assumes EF Core 10; complex types arrived in EF Core 8, and EF Core 10 added struct, optional, JSON and collection support plus ExecuteUpdate on them.