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

📚 Interview question

What is the difference between an entity and a value object in Domain-Driven Design? Explain identity versus structural equality, why value objects should be immutable, whether C# records make good value objects, and how you map value objects with EF Core 10.

Covers entities versus value objects, identity and value equality, immutability, records as value objects, and mapping value objects with EF Core 10 complex types and owned types.

Intermediate Theory Intermediate architecture domain-driven-design ef-core entities records value-objects

🎯 Key points

  • Entity: identity that persists over time; equality by Id, attributes change
  • Value object: no identity; equality by all its values (structural equality)
  • Immutable by design: get-only or init properties, no setters, operations return new instances
  • Value objects validate themselves on creation (no invalid Money or Email can exist)
  • C# record / readonly record struct gives value equality and with-expressions for free
  • Records compare collection members by reference: use ImmutableArray<T> and override Equals with SequenceEqual for structural equality
  • EF Core 10: ComplexProperty is the preferred mapping (struct, optional and JSON-mapped complex types, complex collections in JSON); OwnsOne only when you need a separate table; value converters for single-value types
  • Avoid primitive obsession: Money, EmailAddress, Abn instead of decimal and string

⏱ 30-second answer

An entity has an identity that stays the same while its attributes change: customer #42 is the same customer after moving house. Two entities are equal if their Ids match. A value object has no identity; it is defined by its values, so two Money(100, "AUD") instances are equal. Value objects should be immutable and validate themselves on creation, so an invalid one can never exist.

In C#, a record or readonly record struct gives value equality for free, but the generated equality compares collections by reference, so a value object holding a list needs ImmutableArray<T> and a SequenceEqual-based Equals. In EF Core 10, complex types (ComplexProperty) are the preferred mapping: value semantics, no hidden key, and now struct, optional and JSON-mapped complex types (including complex collections). Use a value converter for single-value types like EmailAddress. The trade-off: more types, far fewer invalid states.

🗣 Full answer (senior)

How I would answer this in an interview

"An entity is something the business tracks over time by identity. An order is still order 1001 after its status changes from Placed to Shipped, so two Order objects are the same order if their Ids match, regardless of their other fields. A value object has no identity at all; it is described entirely by its values. A Money of 100 Australian dollars is interchangeable with any other Money of 100 Australian dollars. So equality for a value object is structural: compare every value.

Because value objects have no identity, they should be immutable. You do not change the amount on a Money; you create a new Money. That makes them safe to share, safe as dictionary keys and easy to reason about. They also validate on creation: an EmailAddress constructor rejects a string without an @, so anywhere in the code that holds an EmailAddress knows it is valid. That is how you get rid of primitive obsession, where a decimal might be dollars or cents and a string might be an ABN or a phone number.

In C# I usually write value objects as records: public sealed record Money(decimal Amount, string Currency) gives value equality, GetHashCode and with expressions. For small ones I use a readonly record struct to avoid allocations. The catch is that record equality on a List<T> member compares references, so a value object holding a list needs a custom Equals. For persistence, EF Core's complex types are now the right default: ComplexProperty maps a Money onto columns in the owner's table with value semantics, and EF Core 10 added struct, optional and JSON-mapped complex types. The mistake I see is making value objects entities by giving them an Id and their own table, just because that is how the ORM worked. My rule: if the business never asks 'which one?', it is a value object."


Entity vs value object

Entity Value object
Identity Yes, an Id that never changes None
Equality By Id By all values
Mutability Mutable through behaviour methods Immutable; replace it
Lifecycle Created, changed, archived Created and discarded
Examples Order, Customer, Policy, Claim Money, Address, DateRange, EmailAddress, Abn
EF Core mapping Entity type with a key Complex type, owned type, or value converter

Choosing a C# shape

Shape When it fits Watch out for
sealed record (class) Most value objects One allocation per instance
readonly record struct Small, hot-path values (2-3 fields) Default value default(Money) bypasses validation
Hand-written class with Equals Collection members, custom equality (case-insensitive email) More code

EF Core 10 mapping options

Option Storage Notes
ComplexProperty Columns in the owner's table, or a JSON column (ToJson) Value semantics; EF Core 10 supports struct, optional and collection (JSON) complex types
OwnsOne / OwnsMany Same table or separate table, or JSON Owned types have a hidden key; reference semantics; older but still supported
Value converter One column Best for single-value types: EmailAddress, OrderId

Production example

In a [billing] service, amounts were plain decimal and some code treated them as cents. Introducing a Money record that carried the currency and rejected negative values found [three] mixed-unit bugs in the first week through compile errors alone, and the mapped complex type kept the same Amount and Currency columns, so no data migration was needed.

🔍 What the interviewer is checking

Checks that the candidate understands identity versus value semantics and can implement and persist value objects in modern C# and EF Core.

Green flags

  • Explains equality by Id versus by value clearly
  • Insists on immutability and self-validation
  • Knows the record collection-equality trap
  • Knows complex types in EF Core 8-10 and when to use converters

Red flags

  • Says value objects are "entities without methods"
  • Gives every value object its own table and Id
  • Unaware that records give value equality

📚 Learn in depth

1. Identity versus equality

Entity                               Value object
------                               ------------
Order #1001 (Placed)                 Money(100, AUD)
      │ status changes                     ==
Order #1001 (Shipped)  same order     Money(100, AUD)   same value

An entity's identity is assigned once (database key, Guid.CreateVersion7(), or a natural key) and never changes. Equality by Id means two in-memory copies loaded separately still compare equal.

2. Why immutability

  • Sharing is safe: two orders can reference the same Address instance without one changing the other.
  • Hash-based collections work: a mutable key in a HashSet gets lost when its hash changes.
  • Validation holds: if it was valid at construction, it is valid forever.
  • Side-effect-free functions: money.Add(other) returns a new Money.

3. How records implement equality

The compiler generates Equals(T? other), GetHashCode, == and != using EqualityComparer<T>.Default for each field, plus an EqualityContract for records so a derived record is not equal to its base. For a List<string> member, EqualityComparer<List<string>>.Default is reference equality, so two value objects with equal lists compare unequal. Fix: store an ImmutableArray<T> and override Equals with SequenceEqual.

4. Validation patterns

 Create("bad") ──► validate ──► fail: Result.Failure / exception
 Create("ok")  ──► validate ──► new EmailAddress("ok")

Use a private constructor plus a static Create factory, or validate in the primary constructor. For a readonly record struct, remember default(T) skips the constructor; guard against it or prefer a class.

5. EF Core mapping internals

  • Complex types (EF Core 8+) have no key and are tracked as part of their owner. Assigning a new instance marks the columns modified. EF Core 9 and 10 broadened support: EF Core 10 adds optional complex types, struct complex types and complex types mapped to JSON, which makes them the recommended default over owned types for value objects.
  • Owned types are really entity types with a shadow key. They work with OwnsMany, but sharing one instance between two owners fails because of identity tracking.
  • Value converters map a single value object to one column (EmailAddress ↔ nvarchar(320)); queries on converted properties can only compare whole values.

6. Strongly typed IDs

An OrderId record struct around a Guid is a value object for identity: it stops you passing a CustomerId where an OrderId is expected. Map it with a value converter.

Try it yourself

  1. Write Money as a record and as a readonly record struct; benchmark creating 1 million with BenchmarkDotNet and compare allocations.
  2. Add a List<string> to a record and show that two equal-looking instances are not equal. Fix it.
  3. Map Address with ComplexProperty in an EF Core 10 app and look at the generated migration.
  4. Replace one string email in your code with an EmailAddress value object and count the compile errors.

💻 Code

Value objects as records, an entity with identity equality, and EF Core 10 mapping.

namespace Billing.Domain;

// Value object: validated, immutable, equality by value.
public sealed record Money
{
    public decimal Amount { get; }
    public string Currency { get; }

    public Money(decimal amount, string currency)
    {
        if (amount < 0) throw new ArgumentOutOfRangeException(nameof(amount));
        if (currency is not { Length: 3 }) throw new ArgumentException("ISO 4217 code required.", nameof(currency));
        Amount = decimal.Round(amount, 2);
        Currency = currency.ToUpperInvariant();
    }

    public Money Add(Money other) =>
        other.Currency == Currency
            ? new Money(Amount + other.Amount, Currency)
            : throw new InvalidOperationException("Cannot add different currencies.");
}

public sealed record Address(string Street, string Suburb, string State, string Postcode);

// Strongly typed id: a value object for identity.
public readonly record struct InvoiceId(Guid Value)
{
    public static InvoiceId New() => new(Guid.CreateVersion7());
}

// Entity: equality by identity, behaviour instead of setters.
public sealed class Invoice
{
    public InvoiceId Id { get; private set; } = InvoiceId.New();
    public Money Total { get; private set; } = new(0, "AUD");
    public Address BillingAddress { get; private set; } = null!;

    private Invoice() { } // for EF Core

    public Invoice(Address billingAddress) => BillingAddress = billingAddress;

    public void AddLine(Money amount) => Total = Total.Add(amount); // replace, not mutate

    public void MoveTo(Address newAddress) => BillingAddress = newAddress;

    public override bool Equals(object? obj) => obj is Invoice other && other.Id == Id;
    public override int GetHashCode() => Id.GetHashCode();
}
using Microsoft.EntityFrameworkCore;
using Billing.Domain;

namespace Billing.Infrastructure;

public sealed class BillingDbContext(DbContextOptions<BillingDbContext> options) : DbContext(options)
{
    public DbSet<Invoice> Invoices => Set<Invoice>();

    protected override void OnModelCreating(ModelBuilder b)
    {
        b.Entity<Invoice>(e =>
        {
            e.HasKey(i => i.Id);
            e.Property(i => i.Id).HasConversion(id => id.Value, v => new InvoiceId(v));

            // Complex types: columns Total_Amount, Total_Currency, BillingAddress_* in the Invoices table.
            e.ComplexProperty(i => i.Total, m =>
            {
                m.Property(x => x.Amount).HasPrecision(18, 2);
                m.Property(x => x.Currency).HasMaxLength(3);
            });
            e.ComplexProperty(i => i.BillingAddress);
        });
    }
}

⚠ Common mistakes

  • Mistake: Giving value objects an Id and their own table. Why it is wrong: it turns them into entities with identity and lifecycle the business does not care about. Instead: map them as complex types in the owner's table.
  • Mistake: Mutable value objects (address.Postcode = "3000"). Why it is wrong: shared instances change unexpectedly and hash-based collections break. Instead: immutable types (get-only or init properties), replaced with with or a new instance.
  • Mistake: Relying on record equality with a List<T> member. Why it is wrong: the generated Equals uses EqualityComparer<List<T>>.Default, which is reference equality, so two value objects with the same items compare unequal and hash differently; and a mutable list also breaks immutability. Instead: store an ImmutableArray<T> (immutable contents) and override Equals and GetHashCode to compare the items with SequenceEqual (structural equality).
  • Mistake: Entities with value equality over all fields. Why it is wrong: the same order before and after a change compares unequal, and two different orders with the same data compare equal. Instead: compare entities by Id.
  • Mistake: Primitive obsession (decimal price, string abn). Why it is wrong: units and formats get mixed and validation is duplicated. Instead: Money, Abn, EmailAddress value objects.
  • Mistake: readonly record struct value objects without guarding default. Why it is wrong: default(Money) skips validation and has a null currency. Instead: use a class record, or check for default where it matters.
  • Mistake: Using OwnsOne by habit in new EF Core 10 code. Why it is wrong: owned types have hidden keys and reference semantics. Instead: prefer ComplexProperty unless you need a separate table.
  • Mistake: Mapping a value object with a list member to a JSON column without thinking about deserialisation. Why it is wrong: EF Core materialises the object through its constructor or backing fields, so a validating constructor that rejects stored legacy data breaks every load. Instead: give EF Core a private constructor or keep stored data valid with a migration, and test round-tripping.

🏛 Senior insight: trade-offs

Value objects are the cheapest DDD pattern with the highest return: they push validation to one place and make illegal states unrepresentable, and they need no architecture change. I introduce them first, even in codebases that will never have aggregates.

Mapping When it fits Cost When not to
ComplexProperty Multi-field value objects (Money, Address) in EF Core 8+ None beyond config You need to query the value object as its own table
Value converter Single-value types, strongly typed IDs Some LINQ limits Multi-field values
OwnsMany / JSON complex collection Small lists owned by an entity JSON querying limits Large or independently queried lists

I measure the payoff by the number of validation checks deleted elsewhere and bugs caught at compile time.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions mapping value objects with EF Core. Why: Checks deeper knowledge of complex types versus owned entities.
    How to 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.

  2. When: Candidate mentions strongly typed IDs or single-value value objects. Why: Checks they can map value objects with value converters and know the query limits.
    How to answer

    A value converter tells EF Core how to turn a .NET value into a column value and back, configured with HasConversion.

    • Enums as strings: HasConversion<string>() plus HasMaxLength(20). Readable in SQL and safe when enum members are reordered.
    • Strongly typed IDs: readonly record struct OrderId(Guid Value) with a ValueConverter<OrderId, Guid>, applied model-wide in ConfigureConventions. The compiler stops you passing a CustomerId where an OrderId belongs.
    • Money has two parts (amount, currency), so it is a complex type, not a converter: converters map one property to one column.

    You need a value comparer when the converted type is mutable (say List<string> stored as JSON), or edits go unnoticed. In LINQ, compare the whole converted value (o.Id == id); o.Id.Value usually doesn't translate. The trade-off: richer domain types versus a few query restrictions.

  3. When: Candidate gives Address as a value object example. Why: Checks that the classification depends on the domain, not the type name.
    How to answer

    It depends on whether the business tracks a specific address over time. For an order it is a value object: a snapshot of where to ship. For a postal service or a property-insurance system, where the address itself has a history, attributes and risk ratings, it is an entity with an Id. Ask the experts: "Do you ever ask which address?"

↩ Usually asked after

More in Domain-Driven Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me