HI WELCOME TO SIRIS

Data Annotations - Required Attribute in EF 6 & EF Core

Leave a Comment

The Required attribute can be applied to one or more properties in an entity class. EF will create a NOT NULL column in a database table for a property on which the Required attribute is applied.

using System.ComponentModel.DataAnnotations;
    
public class Student
{
    public int StudentID { get; set; }
    [Required]
    public string StudentName { get; set; }
}
In the above code, the Required attribute is applied to the StudentName property. So, EF API will create a NOT NULL StudentName column in the Students table, as shown below.
dataannotations required attribute
Now, if you try to save the Student entity without assigning a value to the StudentName property then EF 6 will throw the System.Data.Entity.Validation.DbEntityValidationException exception, while EF Core will throw the Microsoft.EntityFrameworkCore.DbUpdateException exception.
Note: The Required attribute can also be used with ASP.Net MVC as a validation attribute. Visit Implement Validations in ASP.NET MVC for more information.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.