10 Techniques to Improve Your Domain Models

This post is part of the 2026 C# Advent calendar: two C# posts a day, December 1–25.

The Problem

Most “domain models” are anemic, meaning they lack in real behavior and business logic. Many resemble Data Transfer Objects (DTOs) - nothing but a collection of auto-properties. When your core domain models are just bags of properties, the logic of your system has to live somewhere else. And it doesn’t necessarily have to all be in the same place, or in only one place. Anemic domain models lead to business logic duplication and divergence. They lead to more complex, more verbose systems. (I’ve written more about the costs of anemic models before.)

So what can we do about it?

Here’s a list of 10 specific techniques you can apply to your domain models that will generally improve the situation, from a code correctness, testability, and maintainability perspective. Like all design decisions, there are trade-offs, and in high volume systems these designs may lack the necessary performance. But for most business applications and most consumer applications that aren’t chasing massive scale, these practices are usually a good fit.

Each technique below includes a Before example, taken from an anemic model, and an After example, taken from an encapsulated version of the same model. Both come from a simple project and to-do item sample in my DomainModeling repository on GitHub, where you can see the complete code (look in the Endpoints folder in the Web project).

1. Make Setters Private

Make sure your property setters on your domain entities are private. This ensures only the class itself can manipulate its state, and forces state-changing operations to go through well-defined methods. The benefit of using methods is flexibility. If you have two properties that relate to one another and you want to ensure their combination is valid, that’s easily accomplished with a method that sets both together, but much more difficult in individual setters. If your domain model is accessible from the rest of the application, as is common, then any part of the application from the UI to the infrastructure code to the app services can modify entity state at any time. This makes it much more difficult to reason about the state of the domain model, as it has no encapsulation.

You’ll note that encapsulation is the running theme here. If you want to go deeper, see Domain Modeling - Encapsulation and Encapsulation in Objects and Applications.

Before (Anemic/ToDoItem.cs): any code anywhere can change any property.

public class ToDoItem : BaseEntity
{
  public string Name { get; set; } = "";
  public string Description { get; set; } = "";
  public bool IsDone { get; set; }
}

After (EncapsulatedV2/ToDoItem.cs): only the entity can change its own state.

public sealed class ToDoItem : EntityBase
{
  public ToDoItemId Id { get; private set; } = ToDoItemId.Unassigned;
  public ToDoItemName Name { get; private set; }
  public string Description { get; private set; } = "";

  // IsDone only changes through MarkComplete
  public bool IsDone { get; private set; }
}

2. Change State Through Intention-Revealing Methods

This follows partly from the first technique, since once you eliminate public setters, you’re generally forced to use methods for state changes. But instead of just adding a method Update() with a parameter for every property that might be set, take a moment to think about what a logical operation on the model would look like. Use the language of the domain (its ubiquitous language). Instead of setting IsDone to true, call a method MarkComplete(). Instead of expecting callers to remember to set LastUpdatedBy = CurrentUser.UserName require the identity of the user performing the action as part of the method signature (enabling authorization checks within the domain model as well). If your system tracks workflow and the current state, you can map state changes as appropriate method names like “Cancel” or “Approve” instead of just letting any user set the Status to any value at any time.

Encapsulate the behavior. Keep control over the state manipulation logic and provide a place for logic to exist around such changes. This is the Tell, Don’t Ask principle in action: callers tell the model what they want done, rather than asking for its data and making decisions on its behalf. It also helps you make the implicit explicit - a MarkComplete() method documents a business operation in a way that IsDone = true never will.

Before (Anemic/Complete.cs (an API call) and Anemic/UpdateToDoItem.cs): the endpoints set properties directly, and each one has to know what “complete” means.

// Complete a project
project.ToDoItems.ForEach(item => item.IsDone = true);

// Update an item
item.IsDone = request.UpdatedIsDone;
item.Name = request.UpdatedName;

After (EncapsulatedV2/Project.cs and EncapsulatedV2/ToDoItem.cs): the endpoints ask the model to do the work, using the language of the domain.

// Project
public void RenameItem(ToDoItemId itemId, ToDoItemName newName) { /* ... */ }
public void CompleteItem(ToDoItemId itemId) => GetItem(itemId).MarkComplete();
public void CompleteAllItems()
{
  foreach (var item in _toDoItems)
  {
    item.MarkComplete();
  }
}

// ToDoItem
internal void MarkComplete()
{
  if (IsDone) return;

  IsDone = true;
  RegisterDomainEvent(new ToDoItemCompletedEvent(this));
}

The Complete endpoint now just calls project.CompleteAllItems();.

3. Never Let an Object Exist in an Invalid State

The best way to avoid errors related to invalid states, and to avoid the need to constantly validate objects the system depends upon, is to design types so that they cannot represent invalid states. Your system probably has certain invariants - rules that must always be true if the system is in a consistent state. Your calendar expects appointment start time to precede their end times. Your banking system expects deposits to be for positive amounts. Your order system expects every new order to have an associated customer ID.

If your object’s properties all have public setters, then even if you ensure these invariants are true upon creation, there’s nothing to prevent drift as the object interacts with the rest of your code at runtime. Another benefit of requiring intention-revealing methods for state changes is that these methods can ensure only valid changes make it through, and fail fast when something tries to break the rules. Even more important than these mutation methods, though, is the choice of types to use for the object’s state. We’ll see more on this in techniques 5 and 9.

Before (Anemic/Project.cs): a public parameterless constructor and public setters mean a project with no name is perfectly legal.

public class Project : BaseEntity
{
  public string Name { get; set; } = "";
  public List<ToDoItem> ToDoItems { get; set; } = new();
}

var project = new Project(); // Compiles. Name is "".

After (EncapsulatedV2/Project.cs): the only public way to build a project requires a valid name. The parameterless constructor is private, and exists only so EF Core can load saved projects.

public sealed class Project : EntityBase, IAggregateRoot
{
  // For EF Core rehydration only
  private Project() { }

  private Project(ProjectName name)
  {
    Name = name;
  }

  public ProjectName Name { get; private set; }
}

4. Separate Creation from Rehydration with Factory Methods

It’s not uncommon to want to perform some special logic when a new entity is created. Maybe a notification needs to be sent, or a command needs to be queued up for additional processing. If your entities just use constructors and the new keyword for construction, then it can be difficult to know from within the entity whether it is truly being created for the first time in the system, or if it’s simply being deserialized from the database by an ORM tool like Entity Framework Core. A simple pattern for ensuring you always know when the intention of the system is to actually create a new thing is to use a Factory Method for entity creation (and a private constructor, which EF Core and the factory method both can call).

A factory method also gives the operation a name. Project.Create(...) reads like a business action, and if you later need Project.CreateFromTemplate(...) or Project.Import(...), each can have its own rules and side effects without a tangle of constructor overloads.

Before (Anemic/AnemicDbContext.cs): creating a new project and loading an existing one look exactly the same to the entity.

var project = new Project { Name = "First Project!" };

After (EncapsulatedV2/Project.cs): Create is the one path for brand-new projects. EF Core uses the private constructor, so anything that should happen only on true creation, such as raising a ProjectCreated event, goes in the factory method.

public static Project Create(ProjectName name) => new(name);

// Usage
var project = Project.Create(ProjectName.From("First Project!"));

5. Encapsulate Collections

Making setters private isn’t enough when a property is a collection. A private set on a List<T> property stops callers from replacing the list, but they can still add, remove, and clear items to their heart’s content. Every rule about what the collection may contain - a maximum size, no duplicates, items that must be in a certain state - is now enforced only if every caller remembers to enforce it. This is the Exposing Collection Properties antipattern.

Instead, keep the mutable collection in a private field and expose a read-only view of it, such as IReadOnlyCollection<T> or IEnumerable<T>. Then add methods like AddItem and RemoveItem that are the only way to change its contents. Using AsReadOnly() matters here: if you simply return the List<T> typed as IEnumerable<T>, a caller can cast it back to a list and modify it.

EF Core has supported mapping navigation properties to private backing fields for years, so persistence is no longer a good excuse for exposing the list. I cover the details in Avoid Exposing Collections Directly as Properties and Encapsulated Collections in Entity Framework Core.

Before (Anemic/Project.cs and Anemic/AnemicDbContext.cs): callers get the actual List<T>, so they can add, remove, clear, or even replace it.

public List<ToDoItem> ToDoItems { get; set; } = new();

// Usage
project.ToDoItems.Add(new ToDoItem { Name = "Write Sample Code" });

After (EncapsulatedV2/Project.cs and EncapsulatedV2/EncapsulatedV2DbContext.cs): the list is private and callers get a read-only view. EF Core is configured to read and write the backing field.

private readonly List<ToDoItem> _toDoItems = [];

public IReadOnlyCollection<ToDoItem> ToDoItems => _toDoItems.AsReadOnly();

// EF Core configuration
project.Navigation(p => p.ToDoItems).UsePropertyAccessMode(PropertyAccessMode.Field);

// Usage
project.AddItem(ToDoItemName.From("Write Sample Code"));

6. Let the Aggregate Root Guard Its Children

An aggregate is a cluster of related objects that you treat as a single unit for persistence: you load it, change it, and save it together. One entity in the cluster is the aggregate root, and it’s responsible for keeping the whole aggregate consistent. That doesn’t mean the root has to perform every rule check itself. It can, and often should, delegate to its child entities. What matters is that changes that could affect the aggregate’s consistency don’t bypass the root. In our sample, Project is the root and ToDoItem is a child. Outside code can read a project’s items, but if it wants to add, rename, or complete one, it asks the project, which checks the rules only it can see and then hands the change to the item (for example, CompleteItem calls the item’s own MarkComplete).

Why does this matter? Because the root can only protect rules it gets to see. If an endpoint can reach through project.ToDoItems and change an item directly (a Law of Demeter violation, by the way), the project never gets a chance to object. Routing changes through the root means it always gets a say, whether it enforces a rule itself or delegates the work to a child, which sets up the next technique.

In C#, the simplest way to enforce this is to make the child’s constructor and mutation methods internal. That works best when your domain model lives in its own project, since internal means “anything in this assembly.” The sample also marks roots with an IAggregateRoot interface, which makes the boundary explicit and is easy to verify with architecture tests. For more on deciding what belongs in an aggregate, see Aggregate Responsibility Design.

Before (Anemic/UpdateToDoItem.cs): the endpoint reaches past the project and changes the child item directly. The project never gets a say.

var item = project.ToDoItems
    .FirstOrDefault(i => i.Id == request.ToDoItemId);
if (item == null) return NotFound();
item.IsDone = request.UpdatedIsDone;
item.Name = request.UpdatedName;

After (EncapsulatedV2/ToDoItem.cs and EncapsulatedV2/Project.cs): the item’s constructor and mutation methods are internal, so the only way to create or change an item is through its project.

// ToDoItem
internal ToDoItem(ToDoItemName name) { Name = name; }
internal void Rename(ToDoItemName newName) => Name = newName;
internal void MarkComplete() { /* ... */ }

// Project
public ToDoItem AddItem(ToDoItemName name)
{
  EnsureNameIsUnique(name, itemBeingRenamed: null);

  var item = new ToDoItem(name);
  _toDoItems.Add(item);
  return item;
}

public void RenameItem(ToDoItemId itemId, ToDoItemName newName)
{
  var item = GetItem(itemId);
  EnsureNameIsUnique(newName, itemBeingRenamed: item);
  item.Rename(newName);
}

7. Enforce Aggregate-Wide Rules in the Root

Some invariants belong to a single object. A to-do item needs a name, and the item (or better, its name’s type - see technique 9) can enforce that on its own. Other invariants span several objects. “No two items in the same project can have the same name” can’t be checked by any one ToDoItem, because no item knows about its siblings. Only the project sees all of them, so the project is where the rule belongs.

This is the payoff from techniques 5 and 6. Because the collection is encapsulated and every change goes through the root, the root can check its rules before applying any change, and you can be confident there’s no back door. The aggregate becomes a consistency boundary: whatever you load and save together is always valid together.

Be aware of the limits, though. The root can only enforce rules within its own boundary. A rule like “no two projects can share a name” spans many aggregates, and needs a different approach, such as a domain service or a database constraint. I explore those options in Design a No Duplicates Rule in your Domain Model?. And when a rule is violated, throw a specific exception type (or return a specific result) so callers can respond meaningfully, rather than a generic error. See Guard Clauses and Exceptions or Validation? for more on that choice.

Before (Anemic/UpdateToDoItem.cs): nothing stops two items in the same project from having the same name. Enforcing it would mean repeating the check in every endpoint that adds or renames an item.

item.Name = request.UpdatedName; // Duplicate? Nobody checks.

After (EncapsulatedV2/Project.cs and EncapsulatedV2/UpdateToDoItem.cs): “no two items share a name” can’t be checked by a single ToDoItem, because only the project sees all of the items. So the project checks it, and throws a specific exception that callers can turn into a meaningful response.

// Project
private void EnsureNameIsUnique(ToDoItemName name, ToDoItem? itemBeingRenamed)
{
  if (_toDoItems.Any(item => item != itemBeingRenamed && item.Name.IsSameNameAs(name)))
  {
    throw new DuplicateToDoItemNameException(name);
  }
}

// UpdateToDoItem endpoint
try
{
  project.RenameItem(itemId, newName.ValueObject);
}
catch (DuplicateToDoItemNameException ex)
{
  return Conflict(ex.Message);
}

8. Use Strongly-Typed IDs and Reference Other Aggregates by ID

When every ID in your system is an int (or a Guid), the compiler can’t help you when you pass a project ID to a method expecting an item ID. Both are just numbers. This is a common form of primitive obsession, and it produces bugs that compile cleanly, pass casual testing, and show up in production as “why is this user seeing someone else’s data?”

A strongly-typed ID wraps the primitive in its own type: ProjectId, ToDoItemId, CustomerId. Now mixing them up is a compile error. Libraries like Vogen generate the boilerplate, including JSON and EF Core converters, so the database still stores a plain int. Convert raw values to typed IDs once, at the edge of your application (the endpoint, in the sample), and use the typed version everywhere else.

The second half of this technique is about relationships between aggregates. When one aggregate needs to refer to another, hold its ID rather than a navigation property to the other object. If a ToDoItem could be assigned to a user, it would store a UserId AssigneeId, not a User Assignee. This keeps each aggregate small, avoids accidentally loading (or modifying) a whole object graph, and makes the boundaries obvious: if you need the user, you go load the user through its own aggregate root. Strongly-typed IDs make this even safer, since an AssigneeId of type UserId can’t hold anything else. I discuss the trade-offs in more detail in Modeling Navigation Properties Between Aggregates or Modules.

Before (BaseEntity.cs and Anemic/UpdateToDoItem.UpdateToDoItemRequest.cs): every ID is an int, so passing a project ID where an item ID belongs compiles just fine.

public abstract class BaseEntity
{
  public int Id { get; set; }
}

public class UpdateToDoItemRequest
{
  public int ProjectId { get; set; }
  public int ToDoItemId { get; set; }
  // ...
}

After (EncapsulatedV2/Identifiers.cs and EncapsulatedV2/UpdateToDoItem.cs): each entity gets its own ID type (generated here by Vogen), and raw values are converted once, at the edge of the application.

[ValueObject<int>(
  conversions: Conversions.SystemTextJson | Conversions.EfCoreValueConverter,
  deserializationStrictness: DeserializationStrictness.AllowAnything)]
[Instance("Unassigned", 0)]
public readonly partial struct ProjectId
{
  private static Validation Validate(int value) =>
    value > 0 ? Validation.Ok : Validation.Invalid("A project id must be positive.");
}

// UpdateToDoItem endpoint
if (!ProjectId.TryFrom(request.ProjectId, out var projectId)) return NotFound();
if (!ToDoItemId.TryFrom(request.ToDoItemId, out var itemId)) return NotFound();

9. Replace Primitives with Immutable Value Objects

Strongly-typed IDs are one example of a broader technique. Most of the string, int, and decimal properties in a typical domain model actually represent concepts with rules: a name that can’t be blank, an email address with a specific format, a quantity that must be positive, an amount of money in a particular currency. When these are primitives, the rules have to live somewhere else, usually as guard clauses scattered across constructors and methods, often duplicated, and sometimes forgotten.

A value object is a type defined entirely by its values, with no identity of its own. Two ToDoItemName instances with the same text are equal, just like two ints with the same value. Put the validation in the value object’s creation, and make it immutable, and you get a powerful guarantee: if you have an instance, it’s valid. It can’t be created invalid and it can’t be changed to become invalid later. This is the idea behind Parse, Don’t Validate: turn untrusted input into a type that proves it’s valid, once, and let the type carry that proof through the rest of your code. It’s obviously closely related to technique 3 mentioned above, too.

Value objects are also a natural home for behavior. In the sample, ToDoItemName.IsSameNameAs defines what “same name” means (case-insensitive) in exactly one place. For more, see Working with Value Objects, Refactoring to Value Objects, and Support for Value Objects in C#.

Before (Anemic/ToDoItem.cs): a name is any string, including empty, whitespace, or 10,000 characters.

public string Name { get; set; } = "";

After (EncapsulatedV2/Names.cs and EncapsulatedV2/UpdateToDoItem.cs): the rules for a valid name live in one place. Since an invalid ToDoItemName can’t exist, the entity needs no guard clause for it, and the endpoint can turn a bad name into a 400 Bad Request.

// This attribute is from the Vogen (Value Object Generator) package
[ValueObject<string>(conversions: Conversions.SystemTextJson | Conversions.EfCoreValueConverter)]
public readonly partial struct ToDoItemName
{
  public const int MaxLength = 200;

  private static Validation Validate(string value) =>
    string.IsNullOrWhiteSpace(value) ? Validation.Invalid("A to-do item name is required.")
    : value.Length > MaxLength ? Validation.Invalid($"A to-do item name can't be longer than {MaxLength} characters.")
    : Validation.Ok;

  private static string NormalizeInput(string input) => input?.Trim()!;

  public bool IsSameNameAs(ToDoItemName other) =>
    string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase);
}

// UpdateToDoItem endpoint
var newName = ToDoItemName.TryFrom(request.UpdatedName);
if (!newName.IsSuccess) return BadRequest(newName.Error.ErrorMessage);

10. Keep Side Effects Out of Entities with Domain Events

Once your entities own their behavior, it’s tempting to have them do everything related to that behavior. When an item is completed, send an email. When a project is created, call the billing system. But an entity that sends emails needs an email service, and now your domain model depends on infrastructure, is harder to test, and breaks persistence ignorance and its cousins.

Domain events solve this by separating what happened from what to do about it. The entity publishes a simple fact - “this item was completed” - as an event object. Separate handlers, which are free to use any services they need, react to that event. The entity stays focused on its own state and rules, and you can add new reactions without touching it at all.

When the events are dispatched matters. The sample dispatches them only after SaveChangesAsync succeeds, so handlers never act on changes that weren’t persisted. This is still best-effort, in-process dispatch: if a handler fails, the data is already saved. When you need a guarantee that every event is eventually handled, look at the outbox pattern (I show a simple example of it in Building a Resilient Email Sending Method). Note also that MarkComplete does nothing if the item is already done, so completing an item twice doesn’t raise a second event. I wrote about an earlier approach to dispatching in Immediate Domain Event Salvation with MediatR.

Before (Anemic/Complete.cs): completing an item is just a property assignment. If someone needs to be notified, every caller that completes an item has to remember to do it.

project.ToDoItems.ForEach(item => item.IsDone = true);

After (EncapsulatedV2/ToDoItem.cs and EncapsulatedV2/EncapsulatedV2DbContext.cs): the entity announces what happened by registering a domain event. A separate handler sends the notification, and the events are dispatched only after the changes are saved.

// ToDoItem
internal void MarkComplete()
{
  if (IsDone) return;

  IsDone = true;
  RegisterDomainEvent(new ToDoItemCompletedEvent(this));
}

public record ToDoItemCompletedEvent(ToDoItem ToDoItem) : DomainEventBase;

public class CompletedItemHandler : INotificationHandler<ToDoItemCompletedEvent>
{
  public ValueTask Handle(ToDoItemCompletedEvent domainEvent, CancellationToken cancellationToken)
  {
    NotificationService.NotifyToDoItemCompleted(domainEvent.ToDoItem);
    return ValueTask.CompletedTask;
  }
}

// EncapsulatedV2DbContext.SaveChangesAsync (simplified)
var result = await base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
foreach (var domainEvent in domainEvents)
{
  await dispatcher.DispatchAsync(domainEvent, cancellationToken);
}

Conclusion

None of these techniques is new, and none of them requires a rewrite. Each one takes a small amount of control away from “everywhere else” in your application and gives it back to the domain model, where it belongs. Private setters and intention-revealing methods put the model in charge of its own state. Factory methods, encapsulated collections, and aggregate roots make sure every change comes through a door the model controls. Strongly-typed IDs and value objects let the compiler and the type system enforce rules the team would otherwise have to remember. And domain events let the model announce what happened without taking on responsibility for everything that should happen next.

You also don’t need to apply all ten at once. They build on each other, but each one pays off on its own, and the best way to learn them is one at a time, in real code.

So here’s my challenge to you: open the domain model in the app you’re working on right now and pick one entity. Ask yourself a few questions:

  • Does it have public setters that any code can change?
  • Are there rules about its state that live in your endpoints, controllers, or services instead of in the entity?
  • Does it expose a List<T> that callers can modify directly?
  • Are its IDs, names, emails, or amounts just ints, strings, and decimals?

I’d be surprised if you didn’t answer “yes” to at least one. Pick the technique that addresses it, and apply it today. Then let me know how it went, or which technique you’d add to this list, on Bluesky.

References

I’ve covered variations of this topic a few times over the years. Below are some of the related articles and references you may find helpful if you enjoyed this article.

Encapsulation and rich domain models:

Encapsulated collections:

Aggregates:

Value objects and primitive obsession:

State and enum alternatives:

Domain events:

Persistence and application boundaries:

Videos

DevIQ

If you liked this post, consider subscribing to email updates about my new posts, or sharing it on Hacker News.

Keyboard shortcuts

?
Show this help
Esc
Close this help or an open menu
p
Previous (older) post: Developer Docs Deserve Their Own Folder
Tab
Move between links and buttons (Shift+Tab to go back)