Data Annotations C#
Protecting the integrity of the database from the application.
Depending on our needs we can define validations from our application this allows us to have a clearer and simpler definition.
Why implement?
When we write code and at the same time we work with the database we can find ourselves with a dilemma whether to validate within the application or within the database but with Data annotations we can define our validations before the data reaches our database and so save response time and maintain domain integrity of our tables.
Examples:
For this project I am using a C # application in Visual Studio 2017.
We have our data model as an example Account.cs, we must import:
using System.ComponentModel.DataAnnotations;
As we can see we can define validations on different properties even we take off an error message and define regular expressions on a property.
[StringLength(100, MinimumLength = 6, ErrorMessage = "La contraseña debe ser mayor a 6 caracteres")]public String Password { get; set; }
[RegularExpression("(femen|masc)", ErrorMessage = "Masc o femen")]public String Gender { get; set; }
We can add validations on relationships as in this example on a property that when defined [Key] the framework translates it to Primary Key, Autoincrement.
There are more types of annotations (validations, visualization, modeling) and their uses fit our needs any comment or contribution is welcome.
Tnks.