Back to: Entity Framework Tutorials For Begineers and Professionals
Required Attribute in Entity Framework with Examples
In this article, I am going to discuss the Required Data Annotation Attribute in Entity Framework Code First Approach with Examples. Please read our previous article where we discussed NotMapped Attribute in Entity Framework Code First Approach with Examples.
Required Attribute in Entity Framework
The Required Data Annotation Attribute in Entity Framework can be applied to one or more properties of an entity class. If we applied the Required Attribute to a Property, then Entity Framework will create a NOT NULL column for that Property in the database. NOT NULL Column means it will not accept NULL Value in that column in the database.
Now, if you go to the definition of Required Data Annotation Attribute, then you will see the following signature. The Required Attribute belongs to System.ComponentModel.DataAnnotations namespace.
The following Attribute class specifies that a data field value is required. As you can see, this class has one parameterless constructor, one property i.e. AllowEmptyStrings, and one overridden method i.e. IsValid.
Examples to Understand Required Attribute in Entity Framework:
By default, for Nullable .NET Data types such as String, Entity Framework create the column as a NULL column which can accept NULL Values. Let us first understand this default Entity Framework Conventions and then we will see how to use the Required Data Annotation Attribute. First, modify the Student.cs class file as follows.
namespace EFCodeFirstDemo { public class Student { public int StudentId { get; set; } public string Name { get; set; } public string Address { get; set; } public int RollNumber { get; set; } } }
As you can see, here we have created the Student Entity class with four properties. Two Integer properties and two string properties. As the integers are primitive types they cannot hold null value by default. so, for the integer properties, the Entity Framework will create the database column with NOT NULL Constraint which cannot store a null value. The string is a reference type and as they hold a null value by default, so, for string type properties, the Entity Framework is going to create a NULL type column in the database that can store a NULL value.
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.
Now, modify the Main method of the Program class as follows. Here, we are adding one Student entity to the database. As you can see, we have not provided any value for the Address property and by default Address will take the NULL value and that value will be stored in the database.
using System; namespace EFCodeFirstDemo { class Program { static void Main(string[] args) { using (EFCodeFirstContext context = new EFCodeFirstContext()) { var student = new Student() { Name = "Pranaya", RollNumber = 101 }; 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, for integer properties, you will see NOT NULL columns and for string properties, you will see NULL columns as shown in the below image.
How to make the Name Column a NOT NULL Column?
Now, what is our requirement, we need to accept a NULL value for the Address column, but we do not want to accept NULL Value for the Name column. To do so, we need to decorate the Required Data Annotation Attribute with the Name Property of our Student Entity Class. So, modify the Student.cs class file as follows.
using System.ComponentModel.DataAnnotations; namespace EFCodeFirstDemo { public class Student { public int StudentId { get; set; } [Required] public string Name { get; set; } public string Address { get; set; } public int RollNumber { get; set; } } }
Now, modify the Main method of the Program class as follows. As you can see here we are not passing any value for the Name property means by default it will store a Null value.
using System; namespace EFCodeFirstDemo { class Program { static void Main(string[] args) { using (EFCodeFirstContext context = new EFCodeFirstContext()) { var student = new Student() { Address = "Some Address", RollNumber = 101 }; context.Students.Add(student); context.SaveChanges(); Console.WriteLine("Student Added"); Console.ReadKey(); } } } }
With the above changes in place, now run the application code. And this time, you will get the following error.
We are getting the above error because of the Name Column which is created as NOT NULL and here we are trying to store a NULL value. Now, if you check the Students database table, then you will see that the Name database column is created using the NOT NULL constraint as shown in the below image.
Now, let us modify the Main Method of the Program class as follows. As, you can see, here, we are storing an empty string in the Name property of the Student Entity.
using System; namespace EFCodeFirstDemo { class Program { static void Main(string[] args) { using (EFCodeFirstContext context = new EFCodeFirstContext()) { var student = new Student() { Name="", Address = "Some Address", RollNumber = 101 }; context.Students.Add(student); context.SaveChanges(); Console.WriteLine("Student Added"); Console.ReadKey(); } } } }
With the above changes in place, now run the application and this time also you will get the same exception as shown in the below image.
How to allow empty strings in NOT NULL Properties?
Now, our requirement is we will not allow a NULL value, but we want to allow an Empty value. The point that you need to remember is NULL and Empty are not the same, they are different. The value null represents the absence of any object, while the empty string is an object of type String with zero characters.
In order to accept an empty string in a NOT NULL string column, we need to use the AllowEmptyStrings property and we need to set its value to true. This property of the Required Attribute class gets or sets a value that indicates whether an empty string is allowed or not. You need to set the value to true if an empty string is allowed; otherwise, false. The default value is false.
Let us modify the Student Entity class as follows to use Required Attribute with AllowEmptyStrings property and let us set its value to true.
using System.ComponentModel.DataAnnotations; namespace EFCodeFirstDemo { public class Student { public int StudentId { get; set; } [Required(AllowEmptyStrings =true)] public string Name { get; set; } public string Address { get; set; } public int RollNumber { get; set; } } }
With the above changes in place, now run the application. And this time, you will not get any exceptions. The student entity with an empty name is going to be inserted into the Students database table as shown in the below image.
In the next article, I am going to discuss MaxLength and MinLength Attribute in Entity Framework Code First Approach with Examples. Here, in this article, I try to explain Required Data Annotation Attribute in Entity Framework Code First Approach with Examples. I hope you enjoyed this Required Attribute in Entity Framework Code First Approach with Examples article. Please give your valuable feedback and suggestions about this article.