Data Annotations MaxLength/MinLength Attribute in EF 6 & EF Core

The MaxLength Attribute and MinLength Attribute allow us to specify the size of the column. Both these attributes are available in System.ComponentModel.DataAnnotations library. These attributes are similar to StringLength Attribute. Both of these attributes are available in EF 6 & EF Core.

MaxLength Attribute

MaxLength attribute used to set the size of the database column. We can apply this attribute only to the string or array type properties of an entity. The following example shows how to use the MaxLength Attribute

Best Entity Framework Core Books

Best Entity Framework Books

MaxLength Attribute Entity Framework & Entity Framework core
MaxLength Attribute Entity Framework & Entity Framework core

MinLength Attribute

MinLength attribute used to specify the minimum length of string or an array property. It is a validation attribute as it does not change the database schema. The following example shows how to use MinLength attribute

MaxLength and MinLength attribute can be used together as shown below. In this example, Name cannot be greater than 50 characters and cannot be less than 10 characters

You can customize the validation error message displayed to the user using the Error Message parameter of both MaxLength and MinLength attribute as shown below.

Entity framework will throw a validation error ( EntityValidationErrorMaxLength or size is less than a Minlength attribute.

StringLength Attribute

The Entity Framework also supports StringLength attribute, which is used by the ASP.NET MVC for validating the model. This attribute is covered in the next tutorial StringLength attribute.

References

  1. MaxLengthAttribute Class
  2. MinLengthAttribute Class
  3. Data Annotations in Entity Framework & Entity Framework Core

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top