Catalog My learning Blog
Full-Stack Developer Course: React, .NET and SQL Server · Phase 7 · Lesson 62 · 8 min read

DDD in C#: Entities, Value Objects, Invariants

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: A Task State Machine, a Value Object and an Aggregate Rule
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Model business rules inside domain types by using entities with behavior, value objects, and aggregates that protect their invariants, distinguish invariants from input validation, map the model to EF Core without weakening it, and see how a rich domain model closes off whole classes of security bugs.

Concept Explanation

An anemic model is a set of classes that are just bags of public properties, with the rules living in services that manipulate them. Martin Fowler named this the Anemic Domain Model in 2003 and called it an antipattern, because any code anywhere can put the object into an invalid state: set a task to Done without a completion date, or give an order a negative quantity. The rules then have to be re-checked everywhere the object is used, and someone will eventually forget. A rich domain model does the opposite. The type owns its rules, and its public surface offers only operations that keep it valid.

Three building blocks cover most of what you need, following Eric Evans's Domain-Driven Design. An entity has an identity that persists as its attributes change: task 42 is the same task after it is renamed. A value object is defined entirely by its attributes and is immutable, such as Money with an amount and a currency, or an email address: two with the same values are interchangeable, and creating one validates it, so an invalid instance can never exist. An aggregate is a cluster of objects treated as a consistency unit with a single entry point, the aggregate root, through which all changes pass. Making the Project the root for its members and tasks means the rule that a project always has at least one admin is enforced in one place.

The critical distinction is between validation and invariants. Validation checks input at the boundary: is this string non-empty, within length, and shaped like an email. Invariants are rules the domain must always uphold no matter who calls: a task can only move from review to done, a project never loses its last admin, a discount never exceeds the price. Validation produces friendly errors for callers, while invariants protect the integrity of the model and should throw or return failures if violated. Use factory methods or constructors that require valid data, private setters, and methods that express intent, such as MoveTo, Assign, and Archive, rather than exposing properties for arbitrary assignment.

This has direct security value. Mass assignment, discussed on Day 13, is impossible when properties have private setters and the only way to change state is through a method with checks. Privilege escalation through an unexpected code path becomes harder when the rule about who can hold which role lives in the aggregate. And concurrency and transition bugs, like completing an already archived task, are contained in one tested place. EF Core supports this style: private setters and backing fields are mapped by convention or configuration, value objects map as owned types or through value converters, and the aggregate loads and saves as a unit. Keep the model honest in tests: fast unit tests with no database, one per rule.

ConceptDefinitionExample
EntityIdentity persists as attributes changeTaskItem with an Id
Value objectImmutable, equal by value, validated on creationEmail, Money, DateRange
Aggregate rootEntry point that guards a consistency boundaryProject protecting its members
InvariantRule that must always holdA project always has an admin
ValidationInput checks at the boundaryTitle is 1 to 200 characters
Domain methodNamed operation that enforces rulestask.MoveTo(state), project.RemoveMember(id)

Worked Example: A Task State Machine, a Value Object and an Aggregate Rule

The code defines a value object, an entity that guards its transitions, and an aggregate that protects the last-admin invariant, with unit tests and the EF mapping.

C#
// Value object: immutable, validated on creation. An invalid Email cannot exist.
public sealed record Email
{
    public string Value { get; }
    private Email(string value) => Value = value;

    public static Result<Email> Create(string? raw)
    {
        var v = raw?.Trim().ToLowerInvariant();
        if (string.IsNullOrEmpty(v) || v.Length > 254 || !MailAddress.TryCreate(v, out var addr) || addr.Address != v)
            return Result<Email>.Fail("email.invalid", "A valid email address is required.");
        return Result<Email>.Ok(new Email(v));
    }
}

public enum TaskState { Todo = 0, InProgress = 1, Review = 2, Done = 3 }

public sealed class TaskItem
{
    private TaskItem() { }                                             // EF Core only

    public Guid Id { get; private set; }
    public string Title { get; private set; } = "";
    public TaskState State { get; private set; }
    public DateTimeOffset? CompletedAt { get; private set; }
    public byte[] RowVer { get; private set; } = [];

    public static Result<TaskItem> Create(string? title)
    {
        title = title?.Trim();
        if (string.IsNullOrEmpty(title) || title.Length > 200)
            return Result<TaskItem>.Fail("task.title", "A title of 1 to 200 characters is required.");
        return Result<TaskItem>.Ok(new TaskItem { Id = Guid.CreateVersion7(), Title = title, State = TaskState.Todo });
    }

    // Legal transitions live here, once. No caller can skip a step or reopen a finished task by accident.
    private static readonly Dictionary<TaskState, TaskState[]> Allowed = new()
    {
        [TaskState.Todo] = [TaskState.InProgress],
        [TaskState.InProgress] = [TaskState.Todo, TaskState.Review],
        [TaskState.Review] = [TaskState.InProgress, TaskState.Done],
        [TaskState.Done] = [],
    };

    public Result<bool> MoveTo(TaskState next, DateTimeOffset now)
    {
        if (next == State) return Result<bool>.Ok(true);
        if (!Allowed[State].Contains(next))
            return Result<bool>.Fail("task.transition", $"A task cannot move from {State} to {next}.");
        State = next;
        CompletedAt = next == TaskState.Done ? now : null;             // invariant: only done tasks have a completion date
        return Result<bool>.Ok(true);
    }
}

// Aggregate root: all membership changes go through it, so the last-admin rule is enforced in one place.
public sealed class Project
{
    private readonly List<Member> _members = [];
    public Guid Id { get; private set; }
    public IReadOnlyList<Member> Members => _members;

    public Result<bool> ChangeRole(Guid userId, ProjectRole role)
    {
        var member = _members.FirstOrDefault(m => m.UserId == userId);
        if (member is null) return Result<bool>.Fail("member.notfound", "That user is not a member.");
        var admins = _members.Count(m => m.Role == ProjectRole.Admin);
        if (member.Role == ProjectRole.Admin && role != ProjectRole.Admin && admins == 1)
            return Result<bool>.Fail("project.lastadmin", "A project must keep at least one admin.");
        member.Role = role;
        return Result<bool>.Ok(true);
    }

    public Result<bool> RemoveMember(Guid userId)
    {
        var member = _members.FirstOrDefault(m => m.UserId == userId);
        if (member is null) return Result<bool>.Fail("member.notfound", "That user is not a member.");
        if (member.Role == ProjectRole.Admin && _members.Count(m => m.Role == ProjectRole.Admin) == 1)
            return Result<bool>.Fail("project.lastadmin", "A project must keep at least one admin.");
        _members.Remove(member);
        return Result<bool>.Ok(true);
    }
}
Java
// Unit tests: milliseconds, no database. One per rule.
[Fact] public void Cannot_skip_from_todo_to_done() =>
    Assert.Equal("task.transition", NewTask().MoveTo(TaskState.Done, Now).Error!.Code);

[Fact] public void Completion_date_is_set_only_when_done()
{
    var t = NewTaskInReview(); t.MoveTo(TaskState.Done, Now);
    Assert.Equal(Now, t.CompletedAt);
}

[Fact] public void The_last_admin_cannot_be_demoted() =>
    Assert.Equal("project.lastadmin", ProjectWithOneAdmin(out var admin).ChangeRole(admin, ProjectRole.Viewer).Error!.Code);
Code
// EF Core mapping keeps the encapsulation: private setters and backing fields, value objects as converters.
b.Property(t => t.State).HasConversion<byte>();
b.Navigation(p => p.Members).UsePropertyAccessMode(PropertyAccessMode.Field);
b.Property(u => u.Email).HasConversion(e => e.Value, v => Email.Create(v).Value!).HasMaxLength(254);

Notice how mass assignment simply cannot happen: there is no public setter to bind a JSON property to, and the only route from Todo to Done goes through code that checks the rule and sets the completion date consistently.

A task moves Todo to InProgress to Review to Done through a MoveTo method that consults an allowed-transitions table. Skipping a step or reopening a finished task is rejected, and the completion date is set only on Done.
A task moves Todo to InProgress to Review to Done through a MoveTo method that consults an allowed-transitions table. Skipping a step or reopening a finished task is rejected, and the completion date is set only on Done.

Real-World Examples

  • Martin Fowler's 2003 bliki entry on the Anemic Domain Model describes the pattern of domain objects with no behavior as contrary to the basic idea of object-oriented design, which is to combine data and the rules that govern it. Eric Evans's 2003 book Domain-Driven Design gave the vocabulary of entities, value objects, and aggregates that teams still use to discuss these models.
  • Aggregate design guidance from Vaughn Vernon's Effective Aggregate Design articles suggests keeping aggregates small and referencing other aggregates by identity, because large aggregates create contention and slow transactions. It is the practical counterpart to the idea that the aggregate is a consistency boundary: only as much as truly must be consistent together.
Key TakeawaysPut business rules inside domain types rather than scattering them across services and controllers, so the model protects itself. Use entities with intent-revealing methods, immutable value objects that cannot be invalid, and aggregates that enforce invariants at one entry point. Separate input validation from invariants, use private setters so mass assignment is impossible, keep aggregates small, and test each rule with fast unit tests.

Review Questions & Answers

Validation checks input at the boundary and produces user-friendly errors, such as a title being too long. An invariant is a rule the domain must always uphold regardless of who calls it, such as a project always having an admin or a task moving only through legal states. Invariants protect the integrity of the model itself and are enforced inside the domain types.

Properties have private setters and state changes go through methods that check rules, so there is no public property for a deserializer or careless code to set arbitrarily. Privileged fields like roles or completion state can only be changed by the specific operations designed to do so, with their checks attached.

Immutability means it cannot be altered into an invalid state after creation, and validating in the factory means an invalid instance can never exist anywhere in the system. Code receiving an Email can trust it without re-checking, and equality by value makes comparison and testing straightforward.

An aggregate is loaded and saved as one consistency unit, so a large one means more data loaded, longer transactions, and more contention when several users change different parts at once. Keeping the boundary to what truly must be consistent together, and referencing other aggregates by identifier, improves performance and concurrency.