Data annotations are the easiest way to tell a class to enforce some validation rule. You can do the same with the Fluent API. Some people like to do this with data annotations, and some people like it with a free API.
Reasons to like it with data annotations
1) Store the information about the confirmation of my essence in one place along with the definition of the essence
Reasons for Using Fluent API This Way
1) Keep my essence clean. He will have only my property information. There is no verification information. Clean and simple POCO. I will write validation in the OnModelCreating
method in my data context class.
You cannot perform all Fluent API actions using the Data Annotations method. just like you have not a few attributes of data attributes that are not equivalent with the Fluent API (Ex: HasMinLength). HasMinLength
is what we will do to test our model, which usually makes sense in the user interface.
You cannot use the Fluent API only to test the user interface model. The main role of the Fluent API is to look at the current configuration that we are writing and act when creating a model (database) from entities. Remember that we override the OnModelCreating
method to write our current API configuration . Thus, to test the user interface (of my ViewModel), I would use the DataAnnotation method and use the free API if I want to define some thing related to my datamodel, for example Define foreign key or Map this Entity, in a table with a different name etc.
EDIT: According to the editing question
In this case, you should use data annotations. If you make the code first. You may remember that this object will be your database table (of course, you can tell EF to ignore / rename certain columns). In this case, I would keep Entities
clean and Create a ViewModel
, which I will use in my user interface. I will add DataAnnotations
to my ViewModel
to handle it. I can write mapping code that displays data from the ViewModel in Model and Model in ViewModel where necessary.
Shyju source share