Covers implementing a rich Order aggregate in modern C# with a factory method, encapsulated children, invariant checks, a Result type for domain errors, EF Core 10 mapping with backing fields, and a thin application handler.
The aggregate owns its rules. I give Order a private constructor and a static factory Order.Create(customerId, address) that validates and returns a Result<Order>. State has private setters; lines live in a private List<OrderLine> exposed as IReadOnlyCollection. Changes happen only through behaviour methods in the business language (AddLine, Submit, Cancel) that check invariants and return a Result with a domain error (Order.AlreadySubmitted) for expected rule violations; exceptions are kept for bugs.
EF Core 10 maps it through backing fields and a private parameterless constructor, with a rowversion on the root. The application handler stays thin: load, call one method, translate the Result to ProblemDetails, save. The trade-off: a little more code, but every rule is testable in milliseconds with no database.
"I start from the rules, not the table. For an order the rules might be: an order must have a customer and a delivery address; it can have at most 50 lines; quantities are positive; you can't change an order once it is submitted; you can't submit an empty order; and you can only cancel before it ships. Each of those becomes a check inside a method on the aggregate root, so there is no way to put an Order into an invalid state from outside.
Concretely, the constructor is private and creation goes through
Order.Create, which validates and returns aResult<Order>. All properties have private setters. The lines are a privateList<OrderLine>and I exposeIReadOnlyCollection<OrderLine>, soorder.Lines.Adddoesn't compile. Behaviour methods likeAddLineandSubmitreturn aResult. I use results for expected business outcomes, because 'the order is already submitted' is not exceptional, it happens every day, and throwing costs a stack trace and pushes control flow into catch blocks. Exceptions are for programming errors such as a null argument. Each domain error has a stable code, likeorder.already_submitted, which the API maps to a ProblemDetails 409 or 422.For persistence, EF Core 10 handles this shape well: a private parameterless constructor for materialisation,
UsePropertyAccessMode(PropertyAccessMode.Field)on the lines navigation so EF writes to the backing field, value converters for the strongly typed ids, a complex type for the address, and a rowversion on the root. The handler is about ten lines: load the order through the repository, callorder.AddLine, return the failure if there is one, otherwise save. The mistake I see is putting these checks in the handler or a validator: FluentValidation is fine for input shape, but 'can this order still change' is a domain rule and belongs on the aggregate."
| Check | Example | Where |
|---|---|---|
| Input shape | Quantity is a number, address fields present | Request validation (FluentValidation, endpoint filter) |
| Domain invariant | Can't add lines to a submitted order | Aggregate method |
| Cross-aggregate rule | Customer is not on credit hold | Handler or domain service before calling the aggregate |
| Concurrency | Two users editing the same order | Rowversion on the root |
| Result | Exception | |
|---|---|---|
| Use for | Expected business outcomes | Bugs, broken assumptions, infrastructure failures |
| Cost | An allocation at most | Stack trace capture, roughly microseconds per throw |
| Caller | Must handle it (visible in the signature) | Can forget; caught far away |
Moving the order rules from three handlers and a stored procedure into the aggregate let us delete [about 400 lines] of duplicated checks. The aggregate's [62] unit tests run in [under 1 second], and a bug where a submitted order could still be edited through a second endpoint disappeared because there was no longer any code path that bypassed the root.
Checks that the candidate can actually write an encapsulated aggregate in modern C#, persist it with EF Core without breaking encapsulation, and keep handlers thin.
Green flags
Red flags
DbContext into the entity +------------------------- Order (root) --------------------------+
create ──►| static Create(...) : Result<Order> |
| AddLine(...) : Result ── checks: Draft? qty>0? <=50 lines? |
| Submit() : Result ── checks: Draft? any lines? |
| Cancel(clock) : Result ── checks: not Shipped |
| |
| private List<OrderLine> _lines (IReadOnlyCollection outside) |
+-----------------------------------------------------------------+
No public setters means the only transitions are the ones the business named.
A constructor can only return an instance or throw. A static factory can return Result<Order>, giving the caller a typed failure. It also names the intent (Order.Create, Order.CreateFromQuote).
Libraries exist (FluentResults, ErrorOr, Ardalis.Result), but a small home-grown type is often enough and keeps the domain free of dependencies. The important parts are an Error with a stable code (for clients and logs) and a message.
_lines, UsePropertyAccessMode(PropertyAccessMode.Field) makes EF Core add loaded lines to the private list directly.AddLine changes Total on the root, so the root row is updated and its rowversion checked.HTTP POST /orders/{id}/lines
│
▼
Handler: order = repo.Get(id) (1 query with Include)
result = order.AddLine(...) (pure, in memory)
if failure ──► 409/422 ProblemDetails with code
uow.SaveChanges() (UPDATE Orders ... WHERE RowVersion=@v; INSERT OrderLines)
Aggregate tests are plain xUnit: construct, call, assert. No DbContext, no mocks. Integration tests with Testcontainers check the mapping round-trips (load what you saved, compare).
order.Lines.Add(...) and confirm it does not compile; try casting to List<OrderLine> and see why AsReadOnly() matters.The aggregate, a minimal Result type, the EF Core mapping, and a thin handler.
namespace Ordering.Domain;
public sealed record Error(string Code, string Message);
public class Result
{
protected Result(Error? error) => Error = error;
public Error? Error { get; }
public bool IsSuccess => Error is null;
public static Result Ok() => new(null);
public static Result Fail(Error error) => new(error);
}
public sealed class Result<T> : Result
{
private Result(T? value, Error? error) : base(error) => Value = value;
public T? Value { get; }
public static Result<T> Ok(T value) => new(value, null);
public static new Result<T> Fail(Error error) => new(default, error);
}
public static class OrderErrors
{
public static readonly Error NotDraft = new("order.not_draft", "Only draft orders can be changed.");
public static readonly Error Empty = new("order.empty", "An order needs at least one line.");
public static readonly Error TooManyLines = new("order.too_many_lines", "An order has at most 50 lines.");
public static readonly Error BadQuantity = new("order.bad_quantity", "Quantity must be positive.");
public static readonly Error Shipped = new("order.shipped", "A shipped order cannot be cancelled.");
}
public readonly record struct OrderId(Guid Value);
public readonly record struct CustomerId(Guid Value);
public sealed record Address(string Street, string Suburb, string State, string Postcode);
public enum OrderStatus { Draft, Submitted, Shipped, Cancelled }
public sealed class OrderLine
{
private OrderLine() { }
internal OrderLine(string sku, int quantity, decimal unitPrice) => (Sku, Quantity, UnitPrice) = (sku, quantity, unitPrice);
public int Id { get; private set; }
public string Sku { get; private set; } = "";
public int Quantity { get; private set; }
public decimal UnitPrice { get; private set; }
}
public sealed class Order
{
private const int MaxLines = 50;
private readonly List<OrderLine> _lines = [];
private Order() { } // EF Core
public OrderId Id { get; private set; }
public CustomerId CustomerId { get; private set; }
public Address DeliveryAddress { get; private set; } = null!;
public OrderStatus Status { get; private set; }
public decimal Total { get; private set; }
public DateTimeOffset? CancelledAt { get; private set; }
public byte[] RowVersion { get; private set; } = [];
public IReadOnlyCollection<OrderLine> Lines => _lines.AsReadOnly();
public static Result<Order> Create(CustomerId customerId, Address address)
{
if (customerId.Value == Guid.Empty) return Result<Order>.Fail(new("order.no_customer", "Customer is required."));
return Result<Order>.Ok(new Order
{
Id = new OrderId(Guid.CreateVersion7()),
CustomerId = customerId,
DeliveryAddress = address,
Status = OrderStatus.Draft
});
}
public Result AddLine(string sku, int quantity, decimal unitPrice)
{
if (Status != OrderStatus.Draft) return Result.Fail(OrderErrors.NotDraft);
if (quantity <= 0) return Result.Fail(OrderErrors.BadQuantity);
if (_lines.Count >= MaxLines) return Result.Fail(OrderErrors.TooManyLines);
_lines.Add(new OrderLine(sku, quantity, unitPrice));
Total = _lines.Sum(l => l.Quantity * l.UnitPrice); // touches the root row, so rowversion is checked
return Result.Ok();
}
public Result Submit()
{
if (Status != OrderStatus.Draft) return Result.Fail(OrderErrors.NotDraft);
if (_lines.Count == 0) return Result.Fail(OrderErrors.Empty);
Status = OrderStatus.Submitted;
return Result.Ok();
}
public Result Cancel(TimeProvider clock)
{
if (Status == OrderStatus.Shipped) return Result.Fail(OrderErrors.Shipped);
Status = OrderStatus.Cancelled;
CancelledAt = clock.GetUtcNow();
return Result.Ok();
}
}
// Infrastructure: EF Core 10 mapping.
b.Entity<Order>(e =>
{
e.HasKey(o => o.Id);
e.Property(o => o.Id).HasConversion(id => id.Value, v => new OrderId(v));
e.Property(o => o.CustomerId).HasConversion(id => id.Value, v => new CustomerId(v));
e.Property(o => o.Status).HasConversion<string>().HasMaxLength(20);
e.Property(o => o.Total).HasPrecision(18, 2);
e.Property(o => o.RowVersion).IsRowVersion();
e.ComplexProperty(o => o.DeliveryAddress);
e.HasMany(o => o.Lines).WithOne().HasForeignKey("OrderId").OnDelete(DeleteBehavior.Cascade);
e.Navigation(o => o.Lines).UsePropertyAccessMode(PropertyAccessMode.Field);
});
// Application: a thin handler (a Minimal API endpoint here).
app.MapPost("/orders/{id:guid}/lines", async (Guid id, AddLineRequest req, IOrderRepository orders, CancellationToken ct) =>
{
var order = await orders.GetAsync(new OrderId(id), ct);
if (order is null) return Results.NotFound();
var result = order.AddLine(req.Sku, req.Quantity, req.UnitPrice);
if (!result.IsSuccess)
return Results.Problem(statusCode: 409, title: result.Error!.Message,
extensions: new Dictionary<string, object?> { ["code"] = result.Error.Code });
await orders.SaveChangesAsync(ct); // DbUpdateConcurrencyException -> 409 via exception handler
return Results.NoContent();
});
public sealed record AddLineRequest(string Sku, int Quantity, decimal UnitPrice);
List<OrderLine> or returning the field directly. Why it is wrong: callers can add or remove lines without checks, or cast back to List<T>. Instead: return _lines.AsReadOnly() as IReadOnlyCollection<T>.Result with stable error codes; throw for bugs.DateTime.UtcNow inside the aggregate. Why it is wrong: time-dependent rules become untestable. Instead: pass a TimeProvider or the timestamp in.DbContext into the aggregate. Why it is wrong: the domain gains infrastructure dependencies and can no longer be unit tested simply. Instead: the handler fetches what the aggregate needs and passes values in.The value of a rich aggregate is that there is exactly one place where an order can change, so rules cannot drift between endpoints, jobs and imports. The cost is more design up front and some EF Core configuration. For a three-field lookup table it is not worth it; for anything with a lifecycle and money attached, it is.
| Error style | When it fits | Cost | When not to |
|---|---|---|---|
Result with error codes |
Expected business failures, APIs that map to ProblemDetails | Slightly more verbose callers | Truly exceptional failures |
| Domain exceptions + global handler | Small teams, rare failures | Hidden control flow, throw cost | High-volume validation paths |
| Library (ErrorOr, FluentResults) | Want rich composition | Dependency in the domain | You need a dependency-free domain |
I measure success by the number of places that write to the Orders table (should be one mapping) and by aggregate test coverage of every named invariant.
An aggregate is a cluster of entities and value objects that must stay consistent together, with one entity as the aggregate root. Outside code talks only to the root, so the root can enforce the invariants: rules that must be true whenever the transaction commits (an order's total equals its lines; a booking never exceeds capacity).
Keep aggregates small: draw the boundary around real invariants, not around every relationship. Reference other aggregates by id (CustomerId), not by object, so loading an order does not drag in the customer. Change one aggregate per transaction; when another aggregate must react, publish a domain event and update it in a separate transaction. The trade-off is eventual consistency between aggregates in exchange for low contention and clear ownership.
I give aggregates a base class with a private list of domain events, raised inside behaviour methods. A SaveChangesInterceptor overrides SavingChangesAsync: it collects events from ChangeTracker.Entries<AggregateRoot>(), clears them, and dispatches them to handlers resolved from the current DI scope. Because this runs before EF Core writes, any changes handlers make to the same DbContext are saved in the same SaveChanges call and transaction. I loop until no new events appear, with a depth limit.
Anything that must leave the process goes to an outbox row, not a broker call. The trade-off: in-transaction handlers give atomicity but make the save slower and the transaction bigger, so they must stay local and fast.
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.
How to tell it (STAR)
**S:** At [company], warehouse staff found [17] orders in one week whose quantities changed after picking. **T:** I was asked to [find the cause and stop it recurring]. **A:** I traced the updates to a new bulk-edit endpoint that skipped the draft check, patched it the same day, then showed the team the [nine] places that wrote to orders. I proposed moving the rules into the aggregate, wrote the first version with tests, and added an architecture test banning public setters in the domain. **R:** Mismatched shipments dropped to [zero] over the next [two months], and we deleted [about 400] lines of duplicated checks.
Last updated 23 Nov 2026.