📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Owned entities or complex types: how do you map value objects such as Address or Money in EF Core 10? Explain table splitting, separate tables and JSON columns, how each behaves in change tracking, and which you would choose today.

Covers mapping value objects in EF Core 10: owned entity types (OwnsOne, OwnsMany, hidden keys, reference semantics), complex types (ComplexProperty, value semantics, optional and collection support, JSON mapping in EF Core 10), table splitting and ToJson, and the current recommendation.

Mid-Level Theory Intermediate complex-types ddd ef-core json-columns owned-entities value-objects

🎯 Key points

  • Value object = no identity, compared by value, usually immutable
  • Owned types (OwnsOne/OwnsMany) are entities with a hidden key: reference semantics, can't share an instance
  • Complex types (configured with ComplexProperty/ComplexCollection, EF Core 8+) have value semantics: no key, can be structs/records
  • EF Core 10: optional complex types (need one required member), complex collections, and complex types mapped to JSON with ToJson()
  • OwnsOne defaults to table splitting; OwnsMany defaults to its own table (or one JSON column with ToJson)
  • JSON columns: flexible but path filters scan unless indexed via computed columns; EF Core 10 can use the native json type on SQL Server 2025/Azure SQL
  • Choose complex types for value objects in EF Core 10; keep owned types for existing models or owned rows in their own table

⏱ 30-second answer

Both map value objects (no identity, compared by value) into the owner's table or a JSON column.

  • Owned entities (OwnsOne, OwnsMany) are really entities with a hidden key. They have reference semantics: you can't assign the same Address instance to two owners, and OwnsMany defaults to a separate table.
  • Complex types (ComplexProperty, EF Core 8+) have value semantics: no key, can be records or structs, and assigning one copies the values. EF Core 10 added optional complex types, complex collections and JSON mapping with ToJson().

Today I default to complex types for value objects, which is also what the EF Core 10 release notes recommend, and keep owned types for models that already use them or need rows in a separate table. The trade-off: columns (table splitting) are indexable and typed; JSON is flexible but harder to index and constrain.

🗣 Full answer (senior)

How I would answer this in an interview

"A value object like Address or Money has no identity of its own. Two addresses with the same fields are the same address. EF Core has had two ways to map these. Owned entity types, with OwnsOne and OwnsMany, have existed since EF Core 2. Under the covers an owned type is an entity: it gets a hidden key, it's tracked as its own entry, and it has reference semantics. That shows up in odd ways: you can't assign the same Address instance to two customers, and replacing an owned instance is treated as deleting one entity and adding another.

Complex types arrived in EF Core 8 and are the proper value-object mapping. They have no key, they're tracked as part of their owner, they can be records or structs, and assigning one simply copies values. EF Core 8 and 9 had gaps: no optional complex types and no collections. EF Core 10 closed most of them: complex types can be optional, can be collections, and can be mapped to a JSON column with ToJson(). The EF Core 10 release notes now advise moving value objects from owned types to complex types where possible.

For storage I choose between table splitting and JSON. By default a complex property becomes columns on the owner's table, like ShippingAddress_Street, which are typed, constrained and indexable. ToJson() puts the whole value in one JSON column; on SQL Server 2025 or Azure SQL with compatibility level 170, EF Core 10 can use the native json type. I use JSON for collections and shapes that vary, columns for anything I filter or index. For example, at [company] we mapped [a list of contact preferences] as a JSON complex collection instead of a child table, which removed a join from the hottest query and cut its time by [about 30%]."


Owned entities vs complex types

Owned entity (OwnsOne/OwnsMany) Complex type (ComplexProperty)
Identity Hidden key None
Semantics Reference Value
Same instance on two owners Not allowed Fine (values copied)
Structs / records Classes only (records OK) Classes, records, structs
Optional Yes Yes since EF Core 10 (needs a required member)
Collections OwnsMany (table or JSON) Since EF Core 10, JSON only on relational providers
JSON mapping ToJson() since EF Core 7 ToJson() since EF Core 10
Separate table OwnsMany default; ToTable for OwnsOne No

Storage options

Storage Schema Good for Watch out
Table splitting (columns) Address_Street, Address_City Filtering, indexing, constraints Many columns
JSON column One nvarchar(max) or json column Collections, variable shapes Indexing needs computed columns
Separate table (owned only) Child table with FK Large owned collections queried relationally A join per load

Production example

Moving Money from an owned type to a complex type removed a class of bugs where reusing a Money instance across two order lines threw "The entity type 'Money' cannot be tracked because another instance... is already being tracked". The schema didn't change because both map to the same Price_Amount/Price_Currency columns.

🔍 What the interviewer is checking

Checks whether the candidate knows the current EF Core way to map value objects and the storage trade-offs.

Green flags

  • Explains reference vs value semantics
  • Knows complex types gained optional, collections and JSON in EF Core 10
  • Chooses columns vs JSON by query pattern
  • Mentions migration impact when switching

Red flags

  • Gives value objects identities
  • Doesn't know complex types exist

📚 Learn in depth

1. What a value object needs from an ORM

  • No identity: equality by value.
  • Lifetime tied to its owner: deleted with it.
  • Replaceable: assigning a new value is an update of columns, not a delete + insert.

Owned types satisfy the first two only partially; complex types satisfy all three.

2. How owned types are tracked

Customer entry  ── owns ──►  Address entry (key = CustomerId, hidden)

Because Address has its own entry keyed by the owner's key, the same instance cannot belong to two owners (identity conflict), and swapping instances changes entries.

3. How complex types are tracked

Customer entry: { Id, Name, ShippingAddress.Street, ShippingAddress.City, ... }

The complex type's properties are part of the owner's entry. DetectChanges compares each nested property; replacing the whole object is just new values.

4. Table splitting vs JSON

-- Table splitting
[ShippingAddress_Street] nvarchar(200) NOT NULL,
[ShippingAddress_City]   nvarchar(100) NOT NULL,

-- ToJson()
[ShippingAddress] nvarchar(max) NOT NULL   -- or json on SQL Server 2025 / Azure SQL (compat 170)

Queries into JSON translate to JSON_VALUE/OPENJSON; to index a JSON path, add a computed column and index it.

5. Optional complex types (EF Core 10)

All-null columns are ambiguous ("no address" vs "address with every field null"). EF Core 10 therefore requires at least one required property on an optional complex type to tell them apart.

Try it yourself

  1. Map Address with OwnsOne, assign one instance to two customers and save; read the exception.
  2. Switch to ComplexProperty and repeat.
  3. Map a List<PhoneNumber> as a complex collection with ToJson() and query Where(c => c.Phones.Any(p => p.Kind == "Mobile")); read the SQL.
  4. Compare the migrations for table splitting and JSON.

💻 Code

Value objects as complex types in EF Core 10: columns for Money and Address, JSON for a collection.

namespace Shop.Domain;

public sealed record Money(decimal Amount, string Currency);
public sealed record Address(string Street, string Suburb, string State, string Postcode);
public sealed record PhoneNumber(string Kind, string Number);

public sealed class Customer
{
    public int Id { get; set; }
    public required string Name { get; set; }
    public required Address BillingAddress { get; set; }
    public Address? PostalAddress { get; set; }           // optional complex type (EF Core 10)
    public Money CreditLimit { get; set; } = new(0m, "AUD");
    public List<PhoneNumber> Phones { get; set; } = [];   // complex collection (EF Core 10, JSON)
}
namespace Shop.Infrastructure;

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Shop.Domain;

public sealed class CustomerConfiguration : IEntityTypeConfiguration<Customer>
{
    public void Configure(EntityTypeBuilder<Customer> b)
    {
        b.ComplexProperty(c => c.BillingAddress, a =>
        {
            a.Property(x => x.Street).HasMaxLength(200);
            a.Property(x => x.Suburb).HasMaxLength(100);
            a.Property(x => x.State).HasMaxLength(3);
            a.Property(x => x.Postcode).HasMaxLength(4).IsFixedLength();
        });

        b.ComplexProperty(c => c.PostalAddress);           // all-null columns = no postal address

        b.ComplexProperty(c => c.CreditLimit, m =>
        {
            m.Property(x => x.Amount).HasPrecision(18, 2);
            m.Property(x => x.Currency).HasMaxLength(3).IsFixedLength();
        });

        b.ComplexCollection(c => c.Phones, p => p.ToJson());  // one JSON column
    }
}
CREATE TABLE [Customers] (
    [Id] int NOT NULL IDENTITY,
    [Name] nvarchar(max) NOT NULL,
    [BillingAddress_Street] nvarchar(200) NOT NULL,
    [BillingAddress_Suburb] nvarchar(100) NOT NULL,
    [BillingAddress_State] nvarchar(3) NOT NULL,
    [BillingAddress_Postcode] nchar(4) NOT NULL,
    [PostalAddress_Street] nvarchar(max) NULL,
    -- ...
    [CreditLimit_Amount] decimal(18,2) NOT NULL,
    [CreditLimit_Currency] nchar(3) NOT NULL,
    [Phones] nvarchar(max) NOT NULL,        -- json on SQL Server 2025 / Azure SQL compat 170
    CONSTRAINT [PK_Customers] PRIMARY KEY ([Id])
);

Confirm the exact builder method names against your EF Core 10 package; the API surface for complex collections was new in 10.0.

⚠ Common mistakes

  • Mistake: Reusing one owned-type instance on two owners. Why it is wrong: owned types have identity, so tracking throws. Instead: complex types, or create a new instance.
  • Mistake: Giving value objects an Id so EF Core can map them. Why it is wrong: they become entities with lifecycles you don't want. Instead: ComplexProperty.
  • Mistake: Putting everything in JSON. Why it is wrong: a filter such as Where(c => c.Settings.Region == "NSW") becomes JSON_VALUE(...) = N'NSW', which can't seek an ordinary index, so it scans and parses every row's document; on a table of [10 million] rows that turns a 2 ms seek into seconds. The database also can't enforce types, lengths or foreign keys inside the document, and updating one field rewrites the whole value. Instead: columns for anything you filter, sort, join or constrain; for the occasional JSON path you must filter on, add a persisted computed column over JSON_VALUE and index it (or a JSON index on SQL Server 2025).
  • Mistake: Making every member of an optional complex type nullable. Why it is wrong: an optional complex type is stored as nullable columns on the owner, and when they are all NULL EF Core materialises the property as null. If every member can legitimately be null, "no address" and "an address with all fields empty" are stored identically, so EF Core 10 rejects the model. Instead: keep at least one required member (e.g. Street), or make the value non-optional.
  • Mistake: Mutating a complex type held by two owners. Why it is wrong: with a mutable class, both owners change in memory. Instead: immutable records or structs.
  • Mistake: Migrating owned types to complex types without checking the migration. Why it is wrong: column names or nullability may change. Instead: compare the migration and keep names with HasColumnName.

🏛 Senior insight: trade-offs

This is a case where the framework's recommendation changed recently, and a senior answer should say so: on EF Core 10, complex types are the default for value objects, and owned types remain mainly for compatibility and for owned collections that need their own table. The storage decision (columns vs JSON) is separate and should be driven by how you query.

Option When it fits Cost When not to
Complex type, columns Address, Money, DateRange you filter on Wide tables Variable-shape data
Complex type, JSON Small collections, preferences Weaker constraints, index via computed columns Data you join or aggregate heavily
Owned type, separate table Large owned collections queried relationally Hidden keys, reference semantics New value objects on EF Core 10
Real entity Things with identity and lifecycle Repositories, FKs Pure values

Measure with the query's logical reads (SET STATISTICS IO ON) and Query Store before moving a child table into JSON.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions ToJson. Why: Checks storage judgement for JSON mapping.
    How to answer

    Use a JSON column (ComplexProperty(...).ToJson() or OwnsOne/OwnsMany(...).ToJson()) for data that is owned by one row, read and written with it, and rarely queried alone: preferences, a variable set of attributes, a snapshot of an address at order time. Use tables when you need to join, filter or aggregate across rows at scale, enforce foreign keys, unique or check constraints, or update parts concurrently. Performance trade-off: reading the whole document with its owner is cheap (one row, no join), but filtering inside JSON means parsing every document unless you index it. On SQL Server, index a property by adding a computed column over JSON_VALUE(Data, '$.Country') and indexing that column; it works on every supported version. EF Core 10 can map to the native json data type on Azure SQL and SQL Server 2025, which stores documents in a binary form that is faster to read; check your target's support for dedicated JSON indexes before relying on them.

  2. When: Candidate discusses identity versus values. Why: Checks connection between value objects and identity.
    How to answer

    Identity int/bigint keys are small (4/8 bytes) and always increasing, so inserts append to the end of the clustered index; the downside is the value only exists after the INSERT. GUIDs can be created anywhere (offline clients, merges, ids before saving) but are 16 bytes, and random GUIDs as a clustered key cause page splits and fragmentation.

    • EF Core's SQL Server provider generates sequential GUIDs client-side by default, ordered the way SQL Server compares uniqueidentifier.
    • Guid.CreateVersion7() is time-ordered by .NET's byte order, but SQL Server compares the last 6 bytes first, so it is not sequential in a SQL Server index.
    • Composite keys (HasKey(x => new { x.A, x.B })), alternate keys (unique, can be FK targets), sequences and HiLo (UseHiLo()) cover the rest.

    The trade-off: identity is simplest and smallest; GUIDs buy distribution at the cost of size and care with clustering.

🛠 Real-world problems: how you handle them

Reused Money instance crashes SaveChanges with a tracking conflict
Situation
An order service at [company] mapped `Money` as an owned type. A new discount feature copied the same `Money` instance onto several order lines.
Signals
`InvalidOperationException: The instance of entity type 'OrderLine.UnitPrice#Money' cannot be tracked because another instance with the same key value is already being tracked` in Application Insights for [about 5%] of checkouts.
Investigation
Reproduced with an integration test; EF Core sensitive logging (local only) showed the owned entries keyed by the owner. Reviewed the model: `OwnsOne(l => l.UnitPrice)`. The same instance on two owners is invalid for owned types.
Resolution
Immediate hotfix: clone the `Money` instance per line. Real fix: migrated `Money` to a complex type on EF Core 10, kept column names with `HasColumnName`, verified the migration was empty for schema changes.
Prevention
Value objects are immutable records mapped as complex types by convention; an integration test assigns one value object to several owners.

How to tell it (STAR)

**S:** At [company] checkouts started failing for about [5%] of orders after we shipped a discount feature. **T:** I needed a quick fix and a proper one. **A:** The error was a tracking conflict on `Money`, which we mapped as an owned type, so EF Core treated each value as an entity with a key. I shipped a clone-per-line hotfix the same day, then moved `Money` to a complex type, kept the same column names so the migration had no schema change, and added a test that shares one value across owners. **R:** Checkout failures dropped to zero and we standardised on complex types for value objects.

↩ Usually asked after

More in EF Core Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me