Introduction
In a Clean Architecture application, the Domain layer is the most important and independent part of the system. It defines business concepts, business rules, and the relationships between those concepts. The Domain layer should not know about Entity Framework Core, SQL Server, ASP.NET Core, HTTP, JSON, or any user interface technology.
In the previous lesson, we created the solution and its layer projects. In this lesson, we will add meaningful domain models to the Domain project. We will use an online ordering system as our example. Customers can place orders, orders contain order items, and each order has a total monetary value with a currency.
The goal is not simply to create several classes. We need to understand which concepts should be entities, how an entity identity should be protected, which objects should be modeled as value objects, and where business responsibilities should live.
Why the Domain Model Matters
In many traditional applications, models are created as direct copies of database tables. These classes often contain only properties, while business rules are distributed across controllers, services, repositories, and other application components. As a result, understanding whether an order is valid requires examining several unrelated parts of the system.
In a domain-oriented design, the model carries as many business rules as possible. For example, rules such as an order cannot be confirmed without items, a cancelled order cannot receive new items, and a product quantity must be greater than zero should be expressed in the Domain layer.
A good domain model does not only carry data; it also makes the conditions that make the data valid explicit.
The Entity Concept
An entity is a domain object identified by its identity and capable of changing state throughout its lifetime. A customer's name or email address may change, but as long as the customer identity remains the same, it is still the same customer.
When designing an entity, ask the following questions:
- Does this object have a persistent identity?
- Is it considered the same object when its properties change?
- Does it have its own business rules or behaviors?
- Is its lifecycle managed independently or by another object?
For example, Customer, Order, and Product can be entities. A product remains the same product even when its price changes. Likewise, an order remains the same order when its status changes from Pending to Confirmed.
A Base Entity Class
Many projects use a base class for entity identities and shared behavior. Keeping this class in the Domain project reduces duplication across different entities.
namespace Shop.Domain.Common;
public abstract class Entity<TId>
{
public TId Id { get; protected set; } = default!;
protected Entity(TId id)
{
if (EqualityComparer<TId>.Default.Equals(id, default))
throw new ArgumentException("Entity id cannot be empty.", nameof(id));
Id = id;
}
protected Entity()
{
}
}The protected set prevents external code from changing the identity. In most domain models, an entity identity should not change after creation. The protected parameterless constructor may be useful for ORM materialization while still preventing general application code from creating an invalid object casually.
Identity Design
Entity identities can use int, long, Guid, or dedicated identity types. For a simple application, Guid is a reasonable choice. However, using the same primitive type for every entity identity makes accidental misuse possible. For example, the compiler cannot prevent a CustomerId from being passed where an OrderId is expected.
For this course, we will initially use Guid. Generating the identity inside the Domain model ensures that a newly created entity receives a valid identity.
namespace Shop.Domain.Customers;
using Shop.Domain.Common;
public sealed class Customer : Entity<Guid>
{
private Customer(Guid id, string firstName, string lastName, string email)
: base(id)
{
FirstName = firstName;
LastName = lastName;
Email = email;
}
public string FirstName { get; private set; }
public string LastName { get; private set; }
public string Email { get; private set; }
public static Customer Create(
string firstName,
string lastName,
string email)
{
if (string.IsNullOrWhiteSpace(firstName))
throw new ArgumentException("First name is required.", nameof(firstName));
if (string.IsNullOrWhiteSpace(lastName))
throw new ArgumentException("Last name is required.", nameof(lastName));
if (string.IsNullOrWhiteSpace(email))
throw new ArgumentException("Email is required.", nameof(email));
return new Customer(
Guid.NewGuid(),
firstName.Trim(),
lastName.Trim(),
email.Trim().ToLowerInvariant());
}
public void ChangeName(string firstName, string lastName)
{
if (string.IsNullOrWhiteSpace(firstName) ||
string.IsNullOrWhiteSpace(lastName))
throw new ArgumentException("A valid name is required.");
FirstName = firstName.Trim();
LastName = lastName.Trim();
}
}The properties use private setters, so external code cannot perform uncontrolled updates such as customer.Email = .... Changes go through behavior methods where additional rules can be added later.
What Is a Value Object?
A value object is an object whose meaning comes from its values rather than from an identity. Two value objects with the same values are considered equal. For example, Money(100, "USD") is equivalent to another Money instance containing the same amount and currency. No separate database identity is required.
Value objects help reduce a problem often called primitive obsession. Instead of using decimal everywhere, we can create a Money type that carries both amount and currency. This helps prevent errors such as adding values expressed in different currencies.
The Money Value Object
namespace Shop.Domain.Common;
public sealed record Money
{
public decimal Amount { get; }
public string Currency { get; }
private Money(decimal amount, string currency)
{
Amount = amount;
Currency = currency;
}
public static Money Create(decimal amount, string currency)
{
if (amount < 0)
throw new ArgumentOutOfRangeException(nameof(amount));
if (string.IsNullOrWhiteSpace(currency))
throw new ArgumentException("Currency is required.", nameof(currency));
var normalizedCurrency = currency.Trim().ToUpperInvariant();
if (normalizedCurrency.Length != 3)
throw new ArgumentException("Currency must be a three-letter code.", nameof(currency));
return new Money(decimal.Round(amount, 2), normalizedCurrency);
}
public Money Add(Money other)
{
if (!string.Equals(Currency, other.Currency, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("Money currencies must match.");
return Create(Amount + other.Amount, Currency);
}
}Using a record is appropriate here because it provides value-based equality. However, a record by itself does not enforce all domain rules. Creation must still be controlled so invalid amounts or currencies cannot be introduced.
The EmailAddress Value Object
namespace Shop.Domain.Customers;
public sealed record EmailAddress
{
public string Value { get; }
private EmailAddress(string value)
{
Value = value;
}
public static EmailAddress Create(string value)
{
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentException("Email is required.", nameof(value));
var normalized = value.Trim().ToLowerInvariant();
if (!normalized.Contains('@') || normalized.StartsWith('@') || normalized.EndsWith('@'))
throw new ArgumentException("Email format is invalid.", nameof(value));
return new EmailAddress(normalized);
}
public override string ToString() => Value;
}Production systems may require more comprehensive email validation. The simplified check above keeps the example focused. Domain validation should express business rules rather than depend on a particular framework.
Relationships and Aggregate Roots
When designing relationships, do not begin by copying database foreign keys into object navigation properties. First determine which object manages which other object's lifecycle from a business perspective.
An order may contain many order items. An order item does not have a meaningful independent lifecycle outside its order. Therefore, Order can be modeled as the aggregate root, while OrderItem is an entity inside the aggregate.
An aggregate root is the entry point for changes inside an aggregate boundary. External code should not modify order items directly. Instead, it should call a behavior such as Order.AddItem.
namespace Shop.Domain.Orders;
using Shop.Domain.Common;
public enum OrderStatus
{
Pending = 1,
Confirmed = 2,
Cancelled = 3
}
public sealed class Order : Entity<Guid>
{
private readonly List<OrderItem> _items = new();
private Order(Guid id, Guid customerId)
: base(id)
{
CustomerId = customerId;
Status = OrderStatus.Pending;
}
public Guid CustomerId { get; private set; }
public OrderStatus Status { get; private set; }
public IReadOnlyCollection<OrderItem> Items => _items.AsReadOnly();
public static Order Create(Guid customerId)
{
if (customerId == Guid.Empty)
throw new ArgumentException("Customer is required.", nameof(customerId));
return new Order(Guid.NewGuid(), customerId);
}
public void AddItem(Guid productId, string productName, Money unitPrice, int quantity)
{
if (Status != OrderStatus.Pending)
throw new InvalidOperationException("Only pending orders can be modified.");
if (productId == Guid.Empty)
throw new ArgumentException("Product is required.", nameof(productId));
if (quantity <= 0)
throw new ArgumentOutOfRangeException(nameof(quantity));
var item = new OrderItem(
Guid.NewGuid(),
productId,
productName,
unitPrice,
quantity);
_items.Add(item);
}
public void Confirm()
{
if (_items.Count == 0)
throw new InvalidOperationException("An order must contain at least one item.");
if (Status != OrderStatus.Pending)
throw new InvalidOperationException("Only pending orders can be confirmed.");
Status = OrderStatus.Confirmed;
}
public void Cancel()
{
if (Status == OrderStatus.Confirmed)
throw new InvalidOperationException("A confirmed order cannot be cancelled.");
Status = OrderStatus.Cancelled;
}
}
public sealed class OrderItem : Entity<Guid>
{
internal OrderItem(
Guid id,
Guid productId,
string productName,
Money unitPrice,
int quantity)
: base(id)
{
ProductId = productId;
ProductName = productName;
UnitPrice = unitPrice;
Quantity = quantity;
}
public Guid ProductId { get; }
public string ProductName { get; }
public Money UnitPrice { get; }
public int Quantity { get; }
public Money GetTotal() =>
Money.Create(UnitPrice.Amount * Quantity, UnitPrice.Currency);
}Because the OrderItem constructor is internal, outside layers cannot freely create order items. Items are added through the order's behavior. This keeps rules such as “only pending orders can be modified” in one place.
Dependency Boundaries in the Domain Layer
The Domain project should not reference Infrastructure or Presentation. Similarly, avoid placing Entity Framework Core or ASP.NET Core attributes such as [Table], [Column], or [Required] on domain entities.
Database mappings will be configured later in the Infrastructure layer using the EF Core Fluent API. This keeps the domain model independent from the database schema. If SQL Server is replaced with another persistence technology, the domain classes should not need to be redesigned.
Common Mistakes
- Copying database tables directly into the domain: A database schema and a domain model do not need to be identical.
- Making everything public: Public setters allow callers to bypass business rules.
- Using primitives everywhere: Concepts such as money, email, and addresses may deserve their own rule-protecting types.
- Thinking only in navigation properties: Lifecycle and responsibility are more important than foreign keys when defining domain relationships.
- Adding an EF Core dependency to the Domain project: Persistence details belong in Infrastructure.
- Leaving entities anemic: A model that only stores properties does not make business behavior explicit.
- Making aggregates unnecessarily large: Putting every related object inside one aggregate can create concurrency and performance problems.
Practice Exercise
Complete the following exercise in the Domain project:
- Create a
Productentity with an identity, name, description, and price. - Prevent empty product names and negative prices.
- Use the
Moneyvalue object for the price. - Add a
Product.ChangePricemethod that accepts only a valid price. - Create an
Orderand add two products throughAddItem. - Verify that an empty order cannot be confirmed.
- Confirm the order and then try to add another item. Observe that the domain rule is enforced.
Do not add a database, migration, or API endpoint yet. The goal is to verify that the domain objects can operate correctly on their own.
Conclusion
In this lesson, we began modeling the Domain layer at the center of Clean Architecture. We learned that entities are identified by identity, while value objects are defined by their values. We also saw how an aggregate root can control changes within an order boundary.
A well-designed domain model is not a passive copy of database tables. It makes business rules visible, prevents invalid states whenever possible, and operates independently of external technologies.
In the next lesson, we will shape the Application layer around this domain model and begin defining use cases. For that reason, keeping the entities and value objects framework-independent is essential for building the remaining layers correctly.