Entity Framework Code First DataAnnotations [MaxLength] and [MinLength] attributes

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


[MaxLength(int)] attribute can be applied to a string or array type property of a domain class. Entity Framework will set the size of a column to the specified value.

using System.ComponentModel.DataAnnotations;

public class Person
    public int PersonID { get; set; }
    [MinLength(3), MaxLength(100)]
    public string PersonName { get; set; }    

The resulting column with the specified column length:

enter image description here

[MinLength(int)] attribute is a validation attribute, it does not affect the database structure. If we try to insert/update a Person with PersonName with length less than 3 characters, this commit will fail. We’ll get a DbUpdateConcurrencyException that we'll need to handle.

using (var db = new ApplicationDbContext())
     db.Staff.Add(new Person() { PersonName = "ng" });
     catch (DbEntityValidationException ex)
          //ErrorMessage = "The field PersonName must be a string or array type with a minimum length of '3'."

Both [MaxLength] and [MinLength] attributes can also be used with asp.net-mvc as a validation attribute.

Got any Entity Framework Question?