StringLength Attribute in Entity Framework

SPONSOR AD

StringLength Attribute in Entity Framework with Examples

In this article, I am going to discuss StringLength Data Annotation Attribute in Entity Framework Code First Approach with Examples. Please read our previous article where we discussed MaxLength and MinLength Attribute in Entity Framework Code First Approach with Examples.

StringLength Attribute in Entity Framework:

The StringLength Data Annotation Attribute in Entity Framework can be applied to the string or Byte[] properties of an entity class. It is similar to the MaxLength and MinLength Attributes i.e. we can set both MinLength and MaxLength using this attribute. If you go to the definition of the StringLength Attribute class, then you will see the following.

StringLength Attribute in Entity Framework with Examples

As you can see, in the above class signature, it is having one constructor which takes maximumLength string parameter which is used to set the size of a corresponding column (nvarchar in SQL Server) in the database. This Attribute class has two properties and the meaning of these properties are as follows:

SPONSOR AD
  1. MaximumLength { get; }: It is used to get or set the maximum length of a string. This is mandatory.
  2. MinimumLength { get; set; }: It is used to get or set the minimum length of a string. This is optional.
Example to Understand StringLength Attribute in Entity Framework:

Let us understand StringLength Attribute with an example. Please modify the Student Entity as follows. Here, you can see, we have applied the MaxLength Attribute with FirstName Property and StringLength Attribute with the LastName Attribute. Here, both MaxLength and StringLength going to do the same thing. That is, they both will specify the maximum characters allowed for a string property which will also set the size of a corresponding database column in the database. Here, we have set the MaxLength and StringLength as 10 characters.

using System.ComponentModel.DataAnnotations;
namespace EFCodeFirstDemo
{
    public class Student
    {
        public int StudentId { get; set; }
        [MaxLength(10)]
        public string FirstName { get; set; }
        [StringLength(10)]
        public string LastName { get; set; }
    }
}

As we are going to update the Student Entity Model many times, in order to avoid the Run-Time Exception when the model changes and when we rerun the application, let us set the database initializer as DropCreateDatabaseIfModelChanges. So, modify the context class as follows. As you can see here, we have registered the Student model within the context class using DbSet.

using System.Data.Entity;
namespace EFCodeFirstDemo
{
    public class EFCodeFirstContext : DbContext
    {
        public EFCodeFirstContext() : base("name=MyConnectionString")
        {
            //Setting the Database Initializer as DropCreateDatabaseIfModelChanges
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<EFCodeFirstContext>());
        }
        
        public DbSet<Student> Students { get; set; }
    }
}

Please make sure to have the connection string with the name MyConnectionString within the app.config file or web.config file as shown in the below image.

StringLength Attribute in Entity Framework

Now, modify the Main method of the Program class as follows. Here, we are adding one Student Entity to the database. There is no validation of the length of the data we are storing in the properties.

using System;
namespace EFCodeFirstDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            using (EFCodeFirstContext context = new EFCodeFirstContext())
            {
                var student = new Student() { FirstName = "Pranaya", LastName = "Rout" };
                context.Students.Add(student);
                context.SaveChanges();
                Console.WriteLine("Student Added");
                Console.ReadKey();
            }
        }
    }
}

With the above changes in place, now run the application and verify the database. Here, you can see, it created the corresponding database columns with the size 10 for both FirstName and LastName as shown in the below image.

StringLength Data Annotation Attribute in Entity Framework Code First Approach with Examples

SPONSOR AD
Setting both Min and Max Length of a Property using Entity Framework:

As we already discussed in our last article, we can apply both MinLength and MaxLength Attribute on a single property. Instead of applying both Attributes, we can use the StringLength Attribute and we can set both Minimum and Maximum allowed characters for that property. The point that you need to remember is, both are going to do the same thing.

For a better understanding, please modify the Student Entity as follows. Here, we have applied both MinLength and MaxLength Attributes on the FirstName property to set the Maximum Length as 10 and Minimum Length as 5. On the other hand, we have applied the StringLength Attribute on the LastName Property and set the Maximum Length as 10 and Minimum Length as 5 using the MinimumLength property.

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

With the above changes in place, now run the application and you should get the following exception as Minimum Number of Characters validation is Failed for LastName.

Differences Between MaxLength and StringLength in Entity Framework

Now, modify the Main method of the Program class as follows. As you can see, we are entering five characters in the LastName property.

using System;
namespace EFCodeFirstDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            using (EFCodeFirstContext context = new EFCodeFirstContext())
            {
                var student = new Student() { FirstName = "Pranaya", LastName = "Kumar" };
                context.Students.Add(student);
                context.SaveChanges();
                Console.WriteLine("Student Added");
                Console.ReadKey();
            }
        }
    }
}

With the above change in place, run the application again and this time you should not get an exception.

Differences Between MaxLength and StringLength in Entity Framework:

MaxLength Data Annotation Attribute is used for the Entity Framework to decide how large to make a string value field when it creates the database. According to MSDN, MaxLength Specifies the maximum length of array or string data allowed in a property.

StringLength is a Data Annotation Attribute that will be used for the validation of user input. According to MSDN StringLength specifies the minimum and maximum length of characters that are allowed in a data field.

SPONSOR AD

So, if your intention is data validation, then use StringLength and if your intention is to decide the database table column length then use MaxLength Attribute. You will not find any differences when you are using both Attributes with Entity Framework Code First Approach. You will see the differences when you are working with ASP.NET MVC or ASP.NET Web API Application to validate the model data.

In the next article, I am going to discuss DatabaseGenerated Attribute in Entity Framework Code First Approach with Examples. Here, in this article, I try to explain StringLength Data Annotation Attribute in Entity Framework Code First Approach with Examples. I hope you enjoyed this StringLength Attribute in Entity Framework Code First Approach with Examples article. Please give your valuable feedback and suggestions about this article.

SPONSOR AD

Leave a Reply

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