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.
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.
"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
EmailAddressconstructor rejects a string without an @, so anywhere in the code that holds anEmailAddressknows it is valid. That is how you get rid of primitive obsession, where adecimalmight be dollars or cents and astringmight 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,GetHashCodeandwithexpressions. For small ones I use areadonly record structto avoid allocations. The catch is that record equality on aList<T>member compares references, so a value object holding a list needs a customEquals. For persistence, EF Core's complex types are now the right default:ComplexPropertymaps 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 | 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 |
| 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 |
| 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 |
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.
Checks that the candidate understands identity versus value semantics and can implement and persist value objects in modern C# and EF Core.
Green flags
Red flags
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.
Address instance without one changing the other.HashSet gets lost when its hash changes.money.Add(other) returns a new Money.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.
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.
OwnsMany, but sharing one instance between two owners fails because of identity tracking.EmailAddress ↔ nvarchar(320)); queries on converted properties can only compare whole values.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.
Money as a record and as a readonly record struct; benchmark creating 1 million with BenchmarkDotNet and compare allocations.List<string> to a record and show that two equal-looking instances are not equal. Fix it.Address with ComplexProperty in an EF Core 10 app and look at the generated migration.string email in your code with an EmailAddress value object and count the compile errors.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);
});
}
}
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.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).decimal price, string abn). Why it is wrong: units and formats get mixed and validation is duplicated. Instead: Money, Abn, EmailAddress value objects.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.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.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.
Both map value objects (no identity, compared by value) into the owner's table or a JSON column.
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.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.
A value converter tells EF Core how to turn a .NET value into a column value and back, configured with HasConversion.
HasConversion<string>() plus HasMaxLength(20). Readable in SQL and safe when enum members are reordered.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.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.
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?"
Last updated 23 Nov 2026.