225
CHAPTER 6 | Tackle Business Complexity in a Microservice with DDD and CQRS Patterns
for entity
validation in EF Core
(neither does the
IValidatableObject.Validate
method), as they have
done since EF 4.x in .NET Framework.
Data annotations and the
IValidatableObject
interface can still be used for model validation during
model binding, prior to the controller’s actions invocation as usual, but
that model is meant to be a
ViewModel or DTO and that’s an MVC or API concern not a domain model concern.
Having made the conceptual difference clear, you can still use data annotations and
IValidatableObject
in the entity class for validation, if your actions receive an entity class
object
parameter, which is not recommended. In that case, validation will occur upon model binding, just
before invoking the action and you can check the controller’s ModelState.IsValid property to check
the result, but then again, it happens in
the controller, not before persisting the entity object in the
DbContext, as it had done since EF 4.x.
You can still implement custom validation in the entity class using data
annotations and the
IValidatableObject.Validate
method, by overriding the DbContext’s SaveChanges method.
You can see a sample implementation for validating
IValidatableObject
entities in
this comment on
GitHub
. That sample doesn’t do attribute
-based validations, but they
should be easy to implement
using reflection in the same override.
However, from a DDD point of view, the domain model is best kept lean with the use of exceptions in
your entity’s
behavior methods, or by implementing the Specification and Notification patterns to
enforce validation rules.
It can make sense to use data annotations at the application layer in ViewModel classes (instead of
domain entities) that will accept input, to allow for model validation within the UI layer. However, this
should not be done at the exclusion of validation within the domain model.
Dostları ilə paylaş: