Monday, October 20, 2014

Handling C#, MVC entity validation errors in a meaningful way

MVC's entity framework is a convenient tool for abstracting databases. However, when something goes wrong the debug messages are not very meaningful. Especially when an entity validation exception occurs.

The following try, catch block catches an entity validation exception and concatenates all validation error messages into a single string. Then this string can be displayed in a debug message.


try
{
   entities.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
   var errorMessages = ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage);
   //Join the list to a single string. 
   var fullErrorMessage = string.Join("; ", errorMessages);
   throw new Exception(fullErrorMessage);
}