Search K
Appearance
Validation is a mechanism to protect your database from creating or updating records with malformed data. An example would be to limit the length of a string entry to prevent security risks.
We recommend always using validation when creating an entity model class, as this will ultimately prevent invalid data from being saved to your database.
Furthermore, validation mechanics will inform users of errors when creating or updating entities.
Validation attributes are bundled in the System.ComponentModel.DataAnnotations
namespace.
This example from the employee model class shows, how different annotations can be used to ensure valid input.
using System.ComponentModel.DataAnnotations;
public class Employee
{
// Property is a database key
[Key]
public int Id { get; init; }
// Limit string length to 50 characters
[MaxLength(50)]
public string Name { get; set; }
// Ensure string is a valid email address
[EmailAddress]
public string Email { get; set; }
// Limit range of numeric inputs
[Range(20,40)]
public int WeeklyHours { get; set; }
// Ensure that value is not null
[Required]
public WorkModels WorkModel { get; set; }
}
You can find a list of all available annotations and their functionality here.
Each annotation will be evaluated before creating or updating an entry. Should any validation fail an error will be thrown and the database will not be updated.