If the entity should be always in valid state (therefore the properties are readonly and can be set only by methods which contains validation), How can I build this entity inside Repository without executing validations, because I suppose that database state is always valid ? Or should i always excecute validations even if the data source is database ?
For example i have this AggregateEntity Customer
public class Customer
{
public int Id { get; private set; }
public string CompanyName { get; private set; }
public string ContactEmailHeadOffice { get; private set; }
private List<Office> _offices = new List<Office>();
public IEnumerable<Office> Offices => _offices.AsReadOnly();
public void AddOffice(Office office, IRemoteDatabaseRepository repository)
{
office.Validate(); // May throw BusinessRuleException.
if (!repository.DoRegistrationTokenExistForThisCustomer(Id, office.RegistrationToken))
{
throw new BusinessRuleException($"Registration token {office.RegistrationToken} does not exist for customer id {Id}.");
};
}
}
But what is recommended way of populating the properties includes _offices
collection ?
What should CustomerRepository.Retrieve(int customerId)
contains ?
I want to avoid unnecessary validation and I want to be able to set the entity properties for the purpose of unit testing and also be able to get populated entity from the database.