Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify max length attribute to match varchar(max)

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) ?

like image 656
frc Avatar asked Oct 31 '16 20:10

frc


People also ask

What is Dataannotations MaxLength attribute?

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.

Which of the following attributes validate string length?

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.


1 Answers

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; }
like image 155
Ivan Stoev Avatar answered Sep 27 '22 17:09

Ivan Stoev