MaxLength and MinLength Attribute in Entity Framework Core

MaxLength and MinLength Attribute in Entity Framework Core

In this article, I will discuss MaxLength and MinLength Data Annotation Attributes in Entity Framework Core (EF Core) with Examples. Please read our previous article discussing Required Attribute in Entity Framework Core with Examples.

MaxLength and MinLength Attribute in Entity Framework Core

The MaxLength Data Annotation Attribute in Entity Framework Core specifies the maximum data length allowed for a property. This MaxLength Attribute will set the corresponding table column size in the database. In simple words, we can say that using MaxLength Data Annotation Attribute, we can set the size of the database column. If we enter a value greater than the specified size, it will throw an exception.

The MinLength Data Annotation Attribute in Entity Framework Core specifies the minimum data length allowed for a property. In this case, it will set the size of the corresponding database table column as max. In simple words, we can say that using MinLength Data Annotation Attribute, we can validate the data length we will store in the property. If we enter a value less than the specified size, it will throw an exception. It is a validation attribute that will not change the database schema.

By default, for string or byte[] properties of an entity, Entity Framework will set the size of the database column as max. For string properties, it will create the column as nvarchar(max), and for byte[] properties, it will create the column as varbinary(max).

MaxLength Attribute:
  • Limits the number of characters allowed in a string field.
  • It can also be applied to byte array properties, limiting the number of bytes in the field.
  • When used with string properties, it affects the underlying database schema, setting the maximum length for the corresponding column.
MinLength Attribute:
  • Specifies the minimum length of the string.
  • Unlike MaxLength, MinLength does not affect the database schema. It’s purely a validation constraint and will be checked when you attempt to save the entity.
Example to Understand MaxLength and MinLength Attribute in EF Core

Let us understand the default convention with an example, and then we will see how to use MinLength and MaxLength Data Annotation Attributes in EF Core. Please modify the Student Entity as follows. Here, we have created the Student Entity with four properties. One Integer Property, two string properties, and one byte[] property. In this case, for string properties, it will set the corresponding database column as nvarchar(max). For the byte[] property, it will set the corresponding database column as varbinary(max).

namespace EFCoreCodeFirstDemo.Entities
{
    public class Student
    {
        public int StudentId { get; set; }
        public string? FirstName { get; set; }
        public string? LastName { get; set; }
        public byte[]? Photo { get; set; }
    }
}

Next, modify the context class as shown below. As you can see, we have registered the Student model within the context class using DbSet.

using Microsoft.EntityFrameworkCore;
namespace EFCoreCodeFirstDemo.Entities
{
    public class EFCoreDbContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"Server=LAPTOP-6P5NK25R\SQLSERVER2022DEV;Database=EFCoreDB;Trusted_Connection=True;TrustServerCertificate=True;");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
        }

        public DbSet<Student> Students { get; set; }
    }
}

With the above changes, open the Package Manager Console and Execute the add-migration and update-database commands as follows. You can give any name to your migration. Here, I am giving DBMig1. The name that you are giving it should not be given earlier.

How to Set the Max Length and Min Length in EF Core?

Now, if you check the Students database table, you will see it created the corresponding database columns with the maximum size shown in the image below.

How to Set the Max Length and Min Length in EF Core?

How to Set the Max Length and Min Length in EF Core?

Now, we need to provide some restrictions on the data that we are going to store in the database. Our requirement is the maximum length for the First Name value is 50 Characters. The Minimum Length for the Last Name value is 5 Characters. We need to use the MaxLength(50) and MinLength(5) Attributes for this.

So, modify the Student Entity Class as follows. We have applied the MaxLength(50) Data Annotation Attribute on the FirstName Property, which will also set the corresponding database column length as 50. If we enter the FirstName value of more than 50 characters, it will throw an exception. Then, we applied the MinLength(5) Data Annotation Attribute with the LastName Property, which will throw an exception if we enter a value of less than 5 characters. For MinLength Attribute, Entity Framework will set the corresponding database column length as max.

using System.ComponentModel.DataAnnotations;
namespace EFCoreCodeFirstDemo.Entities
{
    public class Student
    {
        public int StudentId { get; set; }
        [MaxLength(50)]
        public string? FirstName { get; set; }
        [MinLength(5)]
        public string? LastName { get; set; }
    }
}

With the above changes, open the Package Manager Console and Execute the add-migration and update-database commands as follows. You can give any name to your migration. Here, I am giving DBMig2. The name that you are giving it should not be given earlier.

MaxLength and MinLength Data Annotation Attributes in Entity Framework Core with Examples

If you verify the database, you will see that the FirstName column will be created with size 50, and the LastName column will be created with the size max, as shown in the image below.

MaxLength and MinLength Data Annotation Attributes in Entity Framework Core with Examples

Note: You must remember that Entity Framework validates the MaxLength and MinLength property values. For MaxLength, whatever value you specified will be set as the corresponding database column size. For MinLength, Entity Framework will set the corresponding database column size as max. The MinLength validation will come into the picture when we work with the ASP.NET Core MVC and ASP.NET Core Web API Applications.

How can we set both MaxLength and MinLength Attribute in a Single Property?

Applying both MaxLength and MinLength Attribute in a single Property is also possible. For example, our requirement is to set the Maximum Length of the Student’s first name as 10 Characters and the Minimum Length for the Student’s first name as 5 Characters. Then, we need to use both MaxLength and MinLength Attribute in the FirstName property of the Student Entity as follows.

using System.ComponentModel.DataAnnotations;
namespace EFCoreCodeFirstDemo.Entities
{
    public class Student
    {
        public int StudentId { get; set; }
        [MaxLength(10), MinLength(5)]
        public string? FirstName { get; set; }
        public string? LastName { get; set; }
    }
}

 

StringLength Attribute: In ASP.NET Core, the StringLength attribute is used for model validation. It provides a way to set both minimum and maximum length constraints on a string property. This is particularly useful for input validation when handling form submissions.

Advantages and DisAdvantages of MaxLength and MinLength Attribute in Entity Framework Core

Using the MaxLength and MinLength attributes in Entity Framework Core provides a way to impose constraints on the data and maintain data integrity. Let’s understand their advantages and disadvantages:

Advantages:
  • Data Integrity: MaxLength and MinLength ensure that the data adheres to the set length constraints, preventing errors or inconsistencies in the data.
  • Database Optimization: MaxLength helps optimize storage, as setting appropriate column sizes can save space in the database. For example, a VARCHAR(50) typically uses less storage than a VARCHAR(MAX).
  • Automatic Schema Generation: When using Code First migrations in EF Core, MaxLength will influence the database schema, setting the size of string columns automatically based on the annotation.
  • Consistent Validation: Setting these constraints at the model level ensures consistent validation throughout the application. The validation logic isn’t scattered or duplicated.
  • Expressive Code: Annotations make the model self-documenting. Developers can easily discern the intended length constraints by looking at the model class.
Disadvantages:
  • No Database Impact with MinLength: The MinLength attribute is purely for validation during runtime in EF Core. It doesn’t affect the database schema, meaning you rely on application logic rather than database constraints to ensure data integrity for minimum lengths.
  • Overhead: Applying constraints introduces overhead when saving data, as EF Core needs to validate entities against these constraints during SaveChanges().
  • Less Flexibility for Schema Evolution: If you set a MaxLength and later decide to need a larger column size, you’ll have to modify the model and then create and apply a migration to change the database schema.
  • Error Handling: You must handle validation exceptions arising from violating these constraints. If not handled appropriately, it might result in poor user experiences.
  • Coupling: Data annotations couple the domain model to the persistence layer. This might not be ideal for architectures aiming for a strict separation between domain logic and data persistence.

In conclusion, while MaxLength and MinLength offer a convenient way to enforce data constraints and improve data integrity, developers must be aware of their limitations, especially regarding flexibility and the potential for increased overhead. 

In the next article, I will discuss DatabaseGenerated Attribute in Entity Framework Core with Examples. In this article, I try to explain the MaxLength and MinLength Data Annotation Attributes in Entity Framework Core with Examples. I hope you enjoyed this article’s MaxLength and MinLength Attribute in EF Core with Examples.

Leave a Reply

Your email address will not be published. Required fields are marked *