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.

Get Entity Framework Core Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.