I need a clean and clear way to validate entities without polluting entities with DataAnnotations, knowing that I am using Fluent Api to configure them.
What do you mean by "polluting entities"?
The best way to work with validation is by decorating by attributes ( belonging to namespace System.ComponentModel.DataAnnotations
). With it, Model becomes a complete representation of a record in a database, with support for validation and description of relationships with other entities.
It's okay to use the Fluent API to decorate the data elements of each entity, but of course this work gets bigger for the following reasons:
Attribute designation does not stay with the class that represents the entity. It can stay in the Entity Framework context initialization (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 , causing the programmer to have to write extra code to make an equivalent effort, such as using the Index
attribute with Fluent API .
Should I use DataAnnotations?
Yes.
What is the best way to validate them?
Attributes work by themselves. You do not need to do anything.
If you want, you can write your own validation attributes , herdando ValidationAttribute
.
Or, implement IValidatableObject
in Model . This interface forces the programmer to implement a Validate
method with business rules involving entity data. Here does not exactly involve the Entity Framework: you are more involved with business rules.
In this way, the validation is done natively in two steps: one in the framework 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 submitting the context modifications. This question has an answer on how this can be done .