HI WELCOME TO SIRIS

Data Annotations - StringLength Attribute in EF 6 & EF Core

Leave a Comment

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.

0 comments:

Post a Comment

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