MaxLength/MinLength Attribute in Entity Framework

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. 

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

MaxLength and MinLength Attribute in Entity Framework
MaxLength Attribute Entity Framework

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.

References

  1. MaxLengthAttribute Class
  2. MinLengthAttribute Class

Leave a Comment

Your email address will not be published. Required fields are marked *

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

Scroll to Top