StringLength Attribute in Entity Framework

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 attribute but operates only on string type properties. Code-First will create the column with the MaxLength size set in this attribute. ASP.NET (both MVC & Core ) uses this attribute to validate the input.

Setting the 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 Entity Framework
StringLength Attribute in Entity Framework

Setting 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.


Best Entity Framework Books
The Best Entity Freamework Books, which helps you to get started with Entity Framework  

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

Read More

  1. Entity Framework Tutorial
  2. MaxLength Attribute
  3. MinLength Attribute
  4. Configure the Entity Data Model
  5. Default Conventions in Entity Framework
  6. Data Annotations in Entity Framework
  7. Column Attribute
  8. Fluent API in Entity Framework

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