Setting the maximum string length
The right attribute to set the maximum string length is StringLengthAttribute
.
Problem
We want to define the maximum length of a string column (VARCHAR
, and NVARCHAR
in SQL Server) in the database using attributes, and there are two choices: MaxLengthAttribute
or StringLengthAttribute
.
How to solve it…
The right attribute to use for this is StringLengthAttribute
. This is the one that Entity Framework will look to when creating the schema:
using System.ComponentModel.DataAnnotations; public class MyEntity { public int Id { get; set; } [StringLength(100)] public string Name { get; set; } }
Note
Of course, we can also use fluent mapping for this, but it is not strictly necessary for this simple case.