Entity Framework MaxLength Data Annotation
The MaxLength
attributes allow you to specify additional property validations. It is applied to a property to specify a maximum number of characters or bytes for the column that the property should map to.
The following example specifies that the Title
column in the Books table have a maximum length of 12 characters.
public class Book { public int BookId { get; set; } [MaxLength(12)] public string Title { get; set; } }
If you set a value of Title property greater than the specified length in MaxLength
attribute, EF will throw an EntityValidationError
.
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
MaxLength
attribute can also be used with MinLength
attribute.
public class Book { public int BookId { get; set; } [MaxLength(12), MinLength(5)] public string Title { get; set; } }
ZZZ Projects