Data Annotations - StringLength Attribute in EF 6 & EF Core

The StringLength attribute can be applied to the string properties of an entity class. It specifies the maximum characters allowed for a string property which in turn sets the size of a corresponding column (nvarchar in SQL Server) in the database.

using System.ComponentModel.DataAnnotations;

public class Student
{
    public int StudentID { get; set; }
    [StringLength(50)]
    public string StudentName { get; set; }
}

As you can see in the above code, we have applied the StringLength attribute to a StudentName property. So, EF will create a StudentName column with nvarchar(50) size in the database, as shown below.

dataannotations maxlength attribute

Entity Framework also validates the value of a property for the StringLength attribute if you set a value higher than the specified size. For example, if you set the string value to more than 50 characters, then EF 6 will throw System.Data.Entity.Validation.DbEntityValidationException and EF Core will throw Microsoft.EntityFrameworkCore.DbUpdateException.

Note: The StringLength attribute can also be used in ASP.NET MVC to validate the value of a property. Visit Implement Validations in ASP.NET MVC for more information.