dotnet-domain-modeling
Modeling business domains. Aggregates, value objects, domain events, rich models, repositories.
What this skill does
# dotnet-domain-modeling
Domain-Driven Design tactical patterns in C#. Covers aggregate roots, entities, value objects, domain events, integration events, domain services, repository contract design, and the distinction between rich and anemic domain models. These patterns apply to the domain layer itself -- the pure C# model that encapsulates business rules -- independent of any persistence technology.
**Out of scope:** EF Core configuration and aggregate persistence mapping -- see [skill:dotnet-efcore-architecture]. Tactical EF Core usage (DbContext lifecycle, migrations, interceptors) -- see [skill:dotnet-efcore-patterns]. Input validation at API boundaries -- see [skill:dotnet-validation-patterns]. Choosing between EF Core, Dapper, and ADO.NET -- see [skill:dotnet-data-access-strategy]. Vertical slice architecture and request pipeline patterns -- see [skill:dotnet-architecture-patterns]. Messaging infrastructure and saga orchestration -- see [skill:dotnet-messaging-patterns].
Cross-references: [skill:dotnet-efcore-architecture] for aggregate persistence and repository implementation with EF Core, [skill:dotnet-efcore-patterns] for DbContext configuration and migrations, [skill:dotnet-architecture-patterns] for vertical slices and request pipeline design, [skill:dotnet-validation-patterns] for input validation patterns, [skill:dotnet-messaging-patterns] for integration event infrastructure.
---
## Aggregate Roots and Entities
An aggregate is a cluster of domain objects treated as a single unit for data changes. The aggregate root is the entry point -- all modifications to the aggregate pass through it.
### Entity Base Class
Entities have identity that persists across state changes. Use a base class to standardize identity and equality:
```csharp
public abstract class Entity<TId> : IEquatable<Entity<TId>>
where TId : notnull
{
// default! required for ORM hydration; Id is set immediately after construction
public TId Id { get; protected set; } = default!;
protected Entity() { } // Required for ORM hydration
protected Entity(TId id) => Id = id;
public override bool Equals(object? obj) =>
obj is Entity<TId> other && Equals(other);
public bool Equals(Entity<TId>? other) =>
other is not null
&& GetType() == other.GetType()
&& EqualityComparer<TId>.Default.Equals(Id, other.Id);
public override int GetHashCode() =>
EqualityComparer<TId>.Default.GetHashCode(Id);
public static bool operator ==(Entity<TId>? left, Entity<TId>? right) =>
Equals(left, right);
public static bool operator !=(Entity<TId>? left, Entity<TId>? right) =>
!Equals(left, right);
}
```
### Aggregate Root Base Class
The aggregate root extends `Entity` and collects domain events:
```csharp
public abstract class AggregateRoot<TId> : Entity<TId>
where TId : notnull
{
private readonly List<IDomainEvent> _domainEvents = [];
public IReadOnlyList<IDomainEvent> DomainEvents =>
_domainEvents.AsReadOnly();
protected AggregateRoot() { }
protected AggregateRoot(TId id) : base(id) { }
protected void RaiseDomainEvent(IDomainEvent domainEvent) =>
_domainEvents.Add(domainEvent);
public void ClearDomainEvents() => _domainEvents.Clear();
}
```
### Concrete Aggregate Example
```csharp
public sealed class Order : AggregateRoot<Guid>
{
public CustomerId CustomerId { get; private set; } = default!;
public OrderStatus Status { get; private set; }
public Money Total { get; private set; } = Money.Zero("USD");
private readonly List<OrderLine> _lines = [];
public IReadOnlyList<OrderLine> Lines => _lines.AsReadOnly();
private Order() { } // ORM constructor
public static Order Create(CustomerId customerId)
{
var order = new Order(Guid.NewGuid())
{
CustomerId = customerId,
Status = OrderStatus.Draft
};
order.RaiseDomainEvent(new OrderCreated(order.Id, customerId));
return order;
}
public void AddLine(ProductId productId, int quantity, Money unitPrice)
{
if (Status != OrderStatus.Draft)
throw new DomainException("Cannot modify a non-draft order.");
if (quantity <= 0)
throw new DomainException("Quantity must be positive.");
var line = new OrderLine(productId, quantity, unitPrice);
_lines.Add(line);
RecalculateTotal();
}
public void Submit()
{
if (Status != OrderStatus.Draft)
throw new DomainException("Only draft orders can be submitted.");
if (_lines.Count == 0)
throw new DomainException("Cannot submit an empty order.");
Status = OrderStatus.Submitted;
RaiseDomainEvent(new OrderSubmitted(Id, Total));
}
private void RecalculateTotal() =>
Total = _lines.Aggregate(
Money.Zero(Total.Currency),
(sum, line) => sum.Add(line.LineTotal));
}
```
### Aggregate Design Rules
| Rule | Rationale |
|------|-----------|
| All mutations go through the aggregate root | Enforces invariants in one place |
| Reference other aggregates by ID only | Prevents cross-aggregate coupling; use `CustomerId` not `Customer` |
| Keep aggregates small | Large aggregates cause lock contention and slow loads |
| One aggregate per transaction | Cross-aggregate changes use domain events and eventual consistency |
| Expose collections as `IReadOnlyList<T>` | Prevents external code from bypassing root methods to mutate children |
For the EF Core persistence implications of these rules (navigation properties, owned types, cascade behavior), see [skill:dotnet-efcore-architecture].
---
## Value Objects
Value objects have no identity -- they are defined by their attribute values. Two value objects with the same attributes are equal. In C#, `record` and `record struct` provide natural value semantics.
### Record-Based Value Objects
```csharp
// Simple value object -- wraps a primitive to enforce constraints
public sealed record CustomerId
{
public string Value { get; }
public CustomerId(string value)
{
if (string.IsNullOrWhiteSpace(value))
throw new DomainException("Customer ID cannot be empty.");
Value = value;
}
public override string ToString() => Value;
}
// Composite value object -- multiple properties with validation
public sealed record Address
{
public string Street { get; }
public string City { get; }
public string State { get; }
public string PostalCode { get; }
public string Country { get; }
public Address(string street, string city, string state,
string postalCode, string country)
{
if (string.IsNullOrWhiteSpace(street))
throw new DomainException("Street is required.");
if (string.IsNullOrWhiteSpace(city))
throw new DomainException("City is required.");
if (string.IsNullOrWhiteSpace(postalCode))
throw new DomainException("Postal code is required.");
Street = street;
City = city;
State = state;
PostalCode = postalCode;
Country = country;
}
}
```
### Money Value Object
Money is the canonical example of a multi-field value object with behavior:
```csharp
public sealed record Money
{
public decimal Amount { get; }
public string Currency { get; }
public Money(decimal amount, string currency)
{
if (string.IsNullOrWhiteSpace(currency))
throw new DomainException("Currency is required.");
Amount = amount;
Currency = currency.ToUpperInvariant();
}
public static Money Zero(string currency) => new(0m, currency);
public Money Add(Money other)
{
EnsureSameCurrency(other);
return new Money(Amount + other.Amount, Currency);
}
public Money Subtract(Money other)
{
EnsureSameCurrency(other);
retRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.