frc frc - 1 month ago 13
C# Question

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

Answer

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; }
Comments