StringLength Attribute in EF Core

The StringLength Attribute Allows us to specify the size of the column. This attribute is available in the System.ComponentModel.DataAnnotations.

StringLength Attribute

The StringLength Attribute Specifies both the Min and Max length of characters that we can use in a field. StringLength is somewhat similar to MaxLength and MinLength attributes but operates only on string type properties. EF Core will create the column with the MaxLength size set in this attribute. ASP.Net MVC Core uses this attribute to validate the input.

Max Length

We can set the Max Length as shown below. This attribute affects the schema as it creates the database column with max length.

StringLength Attribute in EF Core
StringLength in Entity Framework Core

Min Length

We can use the StringLength Attribute to set both Max & Min Length of the string as shown below. The Address property cannot be greater than 50 and cannot be less than 10. While Max length affects the schema of the database Min length applies only for validation purpose.

Validation Message

We can customize the validation messages using the error message parameter as shown below.

The entity framework throws a validation error (EntityValidationError), if the string exceeds Max Length or size is less than Min length specified in this attribute.

References

  1. StringLengthAttribute 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