Overview
Domain entities are the core building blocks of your domain model. They represent objects with unique identity and encapsulate business logic and validation rules.Base Classes
DomainEntity
The foundational base class for all domain entities:DomainEntity<TKey, TValidator>. Located in Core.Domain.Entities.DomainEntity.
The type of the entity’s unique identifier (e.g.,
string, Guid, int)The validator type that implements
IValidator and validates this entityProperties
The unique identifier for the entity. Has a protected setter to ensure identity immutability.
Gets whether the entity is valid according to its validator. Automatically triggers validation when accessed.
The validator instance used to validate this entity.
Methods
Returns a list of validation errors for the current entity state. Triggers validation before returning errors.
Executes the validation logic using the entity’s validator. This method is called automatically by
IsValid and GetErrors().IValidate Interface
All domain entities implement theIValidate interface, which provides:
Property indicating if the entity passes all validation rules
Method to retrieve all validation errors
Creating Custom Entities
Basic Entity Example
Here’s how to create a custom domain entity, based onDummyEntity from Domain/Entities/DummyEntity.cs:12:
Design Principles
Encapsulation
Entity properties should have private setters to prevent direct modification from outside the domain layer. This ensures that:- Business rules are always enforced
- State changes go through validated methods
- The Application layer cannot bypass domain logic
Identity Management
- The
Idproperty should be set in constructors - Use
Guid.NewGuid()for new entities or accept an ID for existing entities - The ID should never change after creation (protected setter)
Validation
- All entities are automatically validated through FluentValidation
- Check
IsValidproperty before persisting entities - Use
GetErrors()to retrieve detailed validation messages - Validation occurs automatically when these properties/methods are called
Entity Examples
The architecture includes example entities inDomain/Entities/:
- DummyEntity - Reference implementation showing all patterns
Best Practices
Use Value Objects
Extract complex properties into value objects for better encapsulation
Parameterless Constructor
Always provide a parameterless constructor for ORM frameworks and serialization
Factory Methods
Use static factory methods for complex entity creation logic
Domain Events
Raise domain events when important state changes occur
Related Resources
- Domain Validators - Learn about entity validation
- Value Objects - Implement value object patterns
- Domain Events - Publish domain events from entities