Required Attribute in Entity Framework Core

Required Attribute in Entity Framework Core

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

Required Attribute in Entity Framework Core

The Required Data Annotation Attribute in Entity Framework Core can be applied to one or more properties of an entity class. If we apply 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.

You will see the following signature if you go to the Required Data Annotation Attribute definition. The Required Attribute belongs to the System.ComponentModel.DataAnnotations namespace.

Required Attribute in Entity Framework Core

The above Required 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.

Note: When using Entity Framework Core (EF Core), the Required Data Annotation Attribute is used to specify that a property on an entity must have a value and cannot be null. This attribute is applied to both the database schema (by creating a non-nullable column) and used for model validation when working with ASP.NET Core MVC and Web API Applications.

Examples to Understand Required Attribute in Entity Framework Core:

By default, for Nullable .NET Data types such as String, EF Core creates the column as a NULL column, which can accept NULL Values. Let us first understand this default Entity Framework Core Conventions, and then we will see how to use the Required Data Annotation Attribute. First, modify the Student.cs class file as follows.

namespace EFCoreCodeFirstDemo.Entities
{
    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 values by default. so, for the integer properties, the Entity Framework Core 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, for string type properties, the EF Core will create a NULL type column in the database that can store a NULL value.

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

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 changes in place, open Package Manager Console and Execute the following add-migration and update-database commands. You can give any name to your migration. Here, I am giving DBMigration101. The name that you are giving it should not be given earlier.

Required Attribute in EF Core

If you verify the database, you will see NOT NULL columns for integer properties. You will see NULL columns for string properties, as shown in the image below.

Required Attribute in Entity Framework Core

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 a NULL Value for the Name column. To do so, we must 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 EFCoreCodeFirstDemo.Entities
{
    public class Student
    {
        public int StudentId { get; set; }
        [Required]
        public string? Name { get; set; }
        public string? Address { get; set; }
        public int RollNumber { get; set; }
    }
}

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

Required Data Annotation Attribute in Entity Framework Core with Examples

If you check the Students database table, you will see that the Name database column is created using the NOT NULL constraint, as shown in the image below.

How to make the Name Column a NOT NULL Column

Uses:
  • Database Level: When migrations are created and applied, EF Core will generate an SQL schema where the column corresponding to the Name property is non-nullable.
  • Runtime Validation: If you attempt to save an entity that violates any of the Required constraints (for instance, if you try to save a Student entity without a Name), EF Core will throw a DbUpdateException.
Example:

Now, to see whether it is working as expected or not, please modify the Main method of the Program class as shown below. As you can see, we are not providing any value for the Name property, and hence, it will take the default value null, and when we call the SaveChanges method, it will throw a runtime exception.

using EFCoreCodeFirstDemo.Entities;
namespace EFCoreCodeFirstDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Student std = new Student()
                {
                    Address = "Test",
                    RollNumber = 1
                };

                using var context = new EFCoreDbContext();
                context.Add(std);
                context.SaveChanges();

                Console.WriteLine("Student added Successfully");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}"); ;
            }
        }
    }
}
How to Restrict 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. It would be best to remember that NULL and Empty are different. 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.

To accept an empty string in a NOT NULL String Column, we need to use the AllowEmptyStrings property and set its value to true. This property of the Required Attribute class gets or sets a value indicating whether an empty string is allowed. 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 Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
namespace EFCoreCodeFirstDemo.Entities
{
    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; }
    }
}
Advantages and Disadvantages of Required Attribute in Entity Framework Core
Advantages of Required Attribute in Entity Framework Core:
  • Data Integrity: By marking a property as Required, we enforce that specific pieces of data are present, maintaining the integrity and consistency of the data in your database.
  • Clear Model Definitions: By marking properties as Required, developers can immediately understand which fields are mandatory, leading to clearer and more understandable entity models.
  • Automatic Validation: EF Core will automatically perform validation checks against entities that use the Required attribute. EF Core will ensure that required fields are populated before changes are saved to the database, reducing the risk of erroneous data entering the database.
  • Database Schema Enforcement: The Required attribute Apply the NOT NULL constraint to the Column in the database, ensuring the rule is enforced at both the application and database levels.
Disadvantages of Required Attribute in Entity Framework Core:
  • Initial Migration Challenges: If you add the Required attribute to an existing property and the database already contains data, you might face challenges when applying the migration. Existing null values in the database will conflict with the new non-nullable constraint. Handling this requires additional work, such as providing default values or cleaning up existing data.
  • Overhead: Validation checks introduce a slight overhead. In most cases, this is negligible, but it’s something to consider if you’re doing bulk inserts or updates.
  • Flexibility: There might be scenarios where a property might change based on evolving business rules or application logic. In such cases, using the Required attribute can be restrictive.

In the next article, I will discuss MaxLength and MinLength Attribute in Entity Framework Core with Examples. I explain the Required Data Annotation Attribute in Entity Framework Core with Examples in this article. I hope you enjoyed this Required Attribute in EF Core with Examples article.

Leave a Reply

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