Class KeyedAggregateRoot<TKey, TBusinessKey>
Base class for aggregates that have both a technical identity and a business key.
public abstract class KeyedAggregateRoot<TKey, TBusinessKey> : AggregateRoot<TKey>, IAggregateRoot<TKey>, IAggregateRoot, IAggregateSnapshotSupport where TKey : notnull where TBusinessKey : notnull
Type Parameters
TKeyThe type of the technical identifier (for persistence).
TBusinessKeyThe type of the business key (domain-meaningful).
- Inheritance
-
AggregateRoot<TKey>KeyedAggregateRoot<TKey, TBusinessKey>
- Implements
-
IAggregateRoot<TKey>
- Inherited Members
Examples
public class OrderAggregate : KeyedAggregateRoot<Guid, string>
{
private string _orderNumber = string.Empty;
public override string BusinessKey => _orderNumber;
protected override bool ApplyEventInternal(IDomainEvent @event) => @event switch
{
OrderCreated e => Apply(e),
_ => false
};
private bool Apply(OrderCreated e)
{
Id = e.OrderId;
_orderNumber = e.OrderNumber;
return true;
}
}
Remarks
Use this base class when:
- The business key may change (e.g., employee badge number after transfer)
- The business key has format constraints from external systems
- The business key is scoped, not globally unique
- Users reference entities by the business key (e.g., order numbers)
- External systems assign the key
Use AggregateRoot<TKey> instead when:
- The domain key IS the technical identity (immutable, globally unique)
- No meaningful business key exists
- Simplicity is preferred
Constructors
KeyedAggregateRoot()
Initializes a new instance of the KeyedAggregateRoot<TKey, TBusinessKey> class.
protected KeyedAggregateRoot()
KeyedAggregateRoot(TKey)
Initializes a new instance of the KeyedAggregateRoot<TKey, TBusinessKey> class with an identifier.
protected KeyedAggregateRoot(TKey id)
Parameters
idTKeyThe unique technical identifier of the aggregate.
Properties
BusinessKey
Gets the domain-meaningful business key for this aggregate.
public abstract TBusinessKey BusinessKey { get; }
Property Value
- TBusinessKey
The business key that identifies this aggregate in the domain.
Remarks
The business key is distinct from Id:
- Id: Technical identity for persistence and event streams (immutable)
- BusinessKey: Domain-meaningful identifier for users and external systems (may change)
Examples: Order number, account number, badge number, SKU.