Data Annotations - Required Attribute in EF 6 & EF Core

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, Required attribute is applied to 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 Student entity without assigning a value to StudentName property then EF 6 will throw System.Data.Entity.Validation.DbEntityValidationException and EF Core will throw Microsoft.EntityFrameworkCore.DbUpdateException exception.

Note: Required attribute can also be used with ASP.Net MVC as a validation attribute. Visit Implement Validations in ASP.NET MVC for more information.