Validate Entity in Entity Framework

Validate Entity in Entity Framework with Examples

In this article, I am going to discuss How to Validate an Entity in Entity Framework Database First Approach with Examples. Please read our previous article where we discussed How to use Transactions in Entity Framework Database First Approach. We are going to work with the same example that we created in our Introduction to Entity Framework Database First Approach article. Please read our Introduction to Entity Framework Database First article before proceeding to this article.

What are the Validations?

Validation is one of the most important features that we need to apply to the data that we are going to store in the database. In simple terms, we can say that validations are nothing but some rules set by the developer on the input data of a web page so as to satisfy the business rules for that particular input data in order to maintain the proper data in a system. There are two types of validations:

  1. Server-Side Validations
  2. Client-Side Validations

While doing validations, as a developer we need to take care of not only the proper validation but also ensure that the validation meets the business rule as per the requirement. From the security point of view, it is also possible that some hackers may bypass client-side validation and insert some vulnerable data into the server.

So, it is always important to provide Client-Side as well as Server-Side Validations while developing web applications.

Validate Entity in Entity Framework:

There are many ways that you can use to implement Server-Side Validations like using Data Annotations, Fluent API, Manual Validation, and many more. If you are using Entity Framework then you can write custom server-side validation to validate an entity. To accomplish so, you just need to override the ValidateEntity method of DbContext and you need to write the custom validation logic.

For example, we need to Validate the Student Entity on the server side. Our business requirement is the First Name, Last Name should not be null or empty. And the Standard ID Property value should be greater than 0. To achieve this, we need to override the ValidateEntity method of DbContext class in our context object. So, copy and paste the following method into the context class.

protected override System.Data.Entity.Validation.DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, System.Collections.Generic.IDictionary<object, object> items)
{
    //If The Entity is of type Student
    if (entityEntry.Entity is Student)
    {
        //If the First Name is Null or Empty
        if (string.IsNullOrEmpty(entityEntry.CurrentValues.GetValue<string>("FirstName")))
        {
            var list = new List<System.Data.Entity.Validation.DbValidationError>();
            list.Add(new System.Data.Entity.Validation.DbValidationError("FirstName", "FirstName is required"));

            return new System.Data.Entity.Validation.DbEntityValidationResult(entityEntry, list);
        }

        if (string.IsNullOrEmpty(entityEntry.CurrentValues.GetValue<string>("LastName")))
        {
            var list = new List<System.Data.Entity.Validation.DbValidationError>();
            list.Add(new System.Data.Entity.Validation.DbValidationError("LastName", "LastName is required"));

            return new System.Data.Entity.Validation.DbEntityValidationResult(entityEntry, list);
        }

        if (entityEntry.CurrentValues.GetValue<int>("StandardId") <= 0)
        {
            var list = new List<System.Data.Entity.Validation.DbValidationError>();
            list.Add(new System.Data.Entity.Validation.DbValidationError("StandardId", "StandardId Value Must be Greater than zero"));

            return new System.Data.Entity.Validation.DbEntityValidationResult(entityEntry, list);
        }
    }
    return base.ValidateEntity(entityEntry, items);
}

As you can see in the above code, we are validating the Student entity. If First Name and Last Name are null or empty, or if the Student ID is less than or equal to 0, then we are adding DBValidationError into DBEntityValidationResult. So, whenever we call the DbContext.SaveChanges method and try to save the Student entity without the First Name, Last Name, or passing some invalid value for the Student ID column, then it will throw a DbEntityValidationException. For a better understanding, please modify the main method as follows.

using System;
using System.Data.Entity.Validation;
namespace DBFirstApproach
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                using (EF_Demo_DBEntities context = new EF_Demo_DBEntities())
                {
                    context.Database.Log = Console.Write;
                    context.Students.Add(new Student() { FirstName = "Rohit", LastName = "", StandardId = 1 });
                    context.Students.Add(new Student() { FirstName = null, LastName = "Kumar", StandardId = 1 });
                    context.Students.Add(new Student() { FirstName = "Rohit", LastName = "Kumar", StandardId = -1 });
                    context.SaveChanges();
                }
            }
            catch (DbEntityValidationException ex)
            {
                foreach (DbEntityValidationResult entityErr in ex.EntityValidationErrors)
                {
                    foreach (DbValidationError error in entityErr.ValidationErrors)
                    {
                        Console.WriteLine($"Error Property Name {error.PropertyName} : Error Message: {error.ErrorMessage}");
                    }
                }
            }

            Console.Read();
        }
    }
}
Output:

How to Validate an Entity in Entity Framework Database First Approach with Examples

In the next article, I am going to discuss DbEntityEntry Class in Entity Framework Database First Approach with Examples. Here, in this article, I try to explain How to Validate Entities in Entity Framework Database First Approach with Examples. I hope you enjoy this How to Validate Entities in Entity Framework Database First Approach article.

Leave a Reply

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