Explicitly Triggering Model Validation Using Entity Framework 6.0

Introduction

With Entity Framework 6.0, when we call the SaveChanges method of the context, context internally validates the entity whose state is not unchanged. We can also disable the validation on the Context's SaveChanges method by setting up the ValidateOnSaveEnabled property of the Context's configuration to false.

Problem Statement

Model Validation is done in the SaveChanges method of the Context, but now I want to prefer to validate my entity elsewhere in my application. How can we do this?

Solution

Using the DbContext.GetValidationErrors method, we can validate our entity anywhere in our application. The SaveChanges method of DbContext calls this method internally to validate the changed or tracked entity. This method returns a collection of DbEntityValidationResults that contain validation results.

Internally this method calls the DetectCahnges() method to determine the states of the tracked entities if DbContext.Configuration.AutoDetectChangesEnabled is set to false. By default this method only validates added or modified entities. The Developer can change this behavior by overriding the ShouldValidateEntity method.

The GetValidationErrors method internally calls the ValidateEntity method of the Context to validate the entities. This ValidateEntity uses the EntityValidator.Validate method to validate the input entity.

GetValidationErrors method definition:

method definition

The GetValidationErrors method returns a DbEntityValidationResult class object. It is never null. Using the DbEntityValidationResult. ValidationErrors property, we can get all the errors of the model.

Example

Suppose there is a DepartmentMaster table in the database and I include this table in my EDMX file. In this table the code field is mandatory. So I have marked this property with the required attribute.

Add model validation using the following data annotation:

  1. namespace ModelValidationinEF6  
  2. {  
  3.     [MetadataType(typeof(DepartmentValidation))]  
  4.     partial class DepartmentMaster  
  5.     {  
  6.         public class DepartmentValidation  
  7.         {  
  8.             [Required]  
  9.             public string Code { getset; }  
  10.         }  
  11.     }  

In the following code example, I get all the errors of the model using the DbContext.GetValidationErrors method.

Example code

  1. static void Main(string[] args)  
  2. {  
  3.     using (Entities Context = new Entities())  
  4.     {  
  5.         DepartmentMaster dept = new DepartmentMaster();  
  6.         dept.Name = "Test";  
  7.         Context.DepartmentMasters.Add(dept);  
  8.         var errors = Context.GetValidationErrors();  
  9.   
  10.         foreach (var error in errors)  
  11.         {  
  12.             if (error.ValidationErrors.Count > 0)  
  13.             {  
  14.                 Console.WriteLine("Error in " + error.Entry.Entity.GetType().Name + " Entity and Errors are as below.");  
  15.                 Console.WriteLine("----------------------------------------------------------------------------");  
  16.                 foreach (var e in error.ValidationErrors)  
  17.                 {  
  18.                     Console.WriteLine("\t\t" + e.PropertyName + " : " + e.ErrorMessage);  
  19.                 }  
  20.                 Console.WriteLine(""); 

Add model validation 

Output

Output

Implicit Validation Execution

If we do not disable the internal validation (using the ValidateOnSaveEnabled property of Configuration set to false) of the DbContext.SaveChanges() method is also validate added or modified entity and it throws the exception if the model is not valid.

model

Conclusion

Using the DbContext. GetValidationErrors method we can explicitly trigger model validation in Entity Framework 6.0. In other words, using this method we can forcefully validate our model.