Thursday, April 12, 2012 #

Entity Framework #3–my scattered notes

When using Entity Framework 4.x Code First you can put your validation code in Data Annotations or inside the DbContext class (this is my preferred mode).

It’s possible to override the virtual method ValidateEntity exposed by the DbContext class and then define your own validation logic in one place.

This method is called once for each distinct entity being modified in your context, and it provides an opportunity for developers to stop the entity update process when some properties are in invalid state.

Here’s an example:

protected override DbEntityValidationResult ValidateEntity(
    DbEntityEntry entityEntry, 
    IDictionary<object, object> items)
{
   var errors = new DbEntityValidationResult(entityEntry, 
                                new List<DbValidationError>());
   if (entityEntry.Entity is Customer)
   {
       Customer customer = (Customer) entityEntry.Entity;
       if (string.IsNullOrEmpty(customer.Lastname))
       {
           var error = new DbValidationError("Lastname", 
                        "Lastname cannot be null or empty");
           errors.ValidationErrors.Add(error);
       }
   }
 
   if (errors.ValidationErrors.Count > 0)
       return errors;
 
   return base.ValidateEntity(entityEntry, items);
}

This code will be invoked only if the “ValidateOnSaveEnabled” property of the class DbContextConfiguration is set to true.

posted @ Thursday, April 12, 2012 9:56 AM | Feedback (0)