I need a clear "clean" way to validate entities without polluting entities with Dataannotations, knowing that I am using the Fluent Api to configure them.
What do you mean "pollute entities"?
The best way to work with validation is by decorating by attributes (belonging to the namespace System.ComponentModel.DataAnnotations
). With her, the Model becomes a complete representation of a record in a database, supporting validation and description of relationships with other entities.
No problem in using the Fluent API to decorate the data elements of each entity, but, of course, this work gets larger for the following reasons:
- The attribute designation is not together with the class representing the entity. It can be on Entity Framework context startup (event
OnModelCreating
) or in a separate class (which inherits EntityMappingConfiguration<T>
);
- The statement is more verbose and not all possible modifiers are in the Fluent API, making the programmer have to write more code to make an equivalent effort, for example, in the use of the attribute
Index
with Fluent API.
I must use Dataannotations?
Yes.
How best to validate them?
Attributes work alone. You don’t have to do anything.
If you want, you can write your own validation attributes, inheriting ValidationAttribute
.
Or else, implement IValidatableObject
in the Model. This interface forces the programmer to implement a method Validate
with the business rules involving the entity’s own data. Here it doesn’t exactly involve the Entity Framework: it’s more involved with the business rules.
In this way, the validation is done natively in two steps: a framework that you are working on (such as ASP.NET MVC, for example, or ASP.NET Data Controls) and another at the database level. The only job the programmer has is to collect the exception messages when sending the context modifications. This question has an answer on how it can be done.
It depends, man... If your application has a user interface, you better create View Models and apply Dataannotation to it... In the domain you apply the business rule and not to risk, validation of data integrity.
– Wilson Santos
Dataannotation attributes have little utility in Viewmodels, as
ScaffoldColumn
andScaffoldTable
, which are bank modifiers.– Leonel Sanches da Silva