I have a model like so:
public int Id { get; set; }
[Required]
[StringLength(50, MinimumLength = 3)]
public string Title { get; set; }
[Required]
[StringLength(50, MinimumLength = 3)]
public string Slug { get; set; }
[Required]
[StringLength(100, MinimumLength = 3)]
public string Body { get; set; }
As you can see for the Body
, I set a limit of 100, but in the database this column is varchar(max)
. What can I put for length to match the column's varchar(max)
?
Data Annotations - MaxLength Attribute in EF 6 & EF Core The MaxLength attribute specifies the maximum length of data value allowed for a property which in turn sets the size of a corresponding column in the database. It can be applied to the string or byte[] properties of an entity.
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.
You have two options:
(1) Use int.MaxLength
as maximumLength
argument of the StringLengthAttribute
constructor:
[Required]
[StringLength(int.MaxValue, MinimumLength = 3)]
public string Body { get; set; }
(2) Decorate the property additionally with MaxLengthAttribute
w/o parameters (the value of the StringLengthAttribute
will be ignored):
[Required]
[StringLength(100, MinimumLength = 3)]
[MaxLength]
public string Body { get; set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With