Entity Framework - Validation


In this chapter let us learn about the validation techniques that can be used in ADO.NET Entity Framework to validate the model data. Entity Framework provides a great variety of validation features that can be implemented to a user interface for client-side validation or can be used for server-side validation.

  • In Entity Framework, data validation is part of the solution for catching bad data in an application.

  • Entity Framework validates all data before it is written to the database by default, using a wide range of data validation methods.

  • However, Entity Framework comes after the user-interface data validation. So in that case there is a need for entity validation to handle any exceptions that EF throws and show a generic message.

  • There are some techniques of data validation to improve your error checking and how to pass error messages back to the user.

DbContext has an Overridable method called ValidateEntity. When you call SaveChanges, Entity Framework will call this method for each entity in its cache whose state is not Unchanged. You can put validation logic directly in here as shown in the following example for the Student Entity.

public partial class UniContextEntities : DbContext {

   protected override System.Data.Entity.Validation
      .DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, 
      System.Collections.Generic.IDictionary<object, object> items) {

         if (entityEntry.Entity is Student) {

            if (entityEntry.CurrentValues.GetValue<string>("FirstMidName") == "") {

               var list = new List<System.Data.Entity
                  .Validation.DbValidationError>();

               list.Add(new System.Data.Entity.Validation
                  .DbValidationError("FirstMidName", "FirstMidName is required"));

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

         if (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);
         }

         return base.ValidateEntity(entityEntry, items);
   }
}

In the above ValidateEntity method, Student entity FirstMidName and LastName properties are checked if any of these property have an empty string, then it will return an error message.

Let’s take a look at a simple example in which a new student is created, but the student’s FirstMidName is empty string as shown in the following code.

class Program {

   static void Main(string[] args) {

      using (var context = new UniContextEntities()) {

         Console.WriteLine("Adding new Student to the database");
         Console.WriteLine();

         try {

            context.Students.Add(new Student() {
               FirstMidName = "",
               LastName = "Upston"
            });

            context.SaveChanges();
         } catch (DbEntityValidationException dbValidationEx) {

            foreach (DbEntityValidationResult entityErr in 
               dbValidationEx.EntityValidationErrors) {

               foreach (DbValidationError error in entityErr.ValidationErrors) {
                  Console.WriteLine("Error: {0}",error.ErrorMessage);
               }
            }
         }

         Console.ReadKey();
      }
   }
}

When the above example is compiled and executed, you will receive the following error message on the console window.

Adding new Student to the database  
Error: FirstMidName is required 

We recommend you to execute the above example in a step-by-step manner for better understanding.

Advertisements