Creating Domain Entities
Domain entities are the core building blocks of your application. This guide walks you through creating entities that inherit fromDomainEntity with proper validation and encapsulation.
Overview
Every domain entity in this architecture must:- Inherit from
DomainEntity<TKey, TValidator> - Have private setters to protect domain invariants
- Include a validator that inherits from
EntityValidator<TEntity> - Use methods to modify properties with validation logic
Step-by-Step Guide
Create the Entity Validator
First, create a validator class using FluentValidation. This defines your business rules.Create a new file in Example from codebase:
Domain/Validators/YourEntityValidator.cs:Domain/Validators/DummyEntityValidator.cs:13-20Create the Domain Entity
Create your entity class that inherits from Example from codebase:
DomainEntity<TKey, TValidator>.Create a new file in Domain/Entities/YourEntity.cs:Domain/Entities/DummyEntity.cs:12-48Understanding DomainEntity Base Class
The Reference:
DomainEntity<TKey, TValidator> base class provides:- Id property: Generic key of type
TKey - IsValid property: Returns true if all validation rules pass
- GetErrors() method: Returns a list of validation errors
- Automatic validation: Runs FluentValidation rules
Core.Domain/Entities/DomainEntity.cs:13-45Use Value Objects for Complex Properties
For properties that represent value objects or enums, define them separately:Then use them in your entity:Example from codebase:
Domain/Entities/DummyEntity.cs:19Key Principles
Why Private Setters?
Why Private Setters?
Private setters enforce encapsulation by ensuring properties can only be modified through entity methods. This allows you to:
- Validate changes before applying them
- Maintain business invariants
- Track modifications and raise domain events
- Prevent invalid state transitions
When to Validate?
When to Validate?
Validation happens automatically when:
- You check the
IsValidproperty - You call
GetErrors()method - The entity is saved (validated in the use case handler)
ID Generation Strategy
ID Generation Strategy
You have two options:
- GUID:
Id = Guid.NewGuid().ToString()(recommended for distributed systems) - Database-generated: Let the database assign the ID
- Custom: Implement your own ID generation logic
Complete Example
Here’s the completeDummyEntity implementation from the codebase:
Domain/Entities/DummyEntity.cs:12-48
Next Steps
Implementing Use Cases
Learn how to create commands and queries that work with your entities
Database Setup
Configure Entity Framework to persist your entities