Skip to content

Instantly share code, notes, and snippets.

@rodrimaia
Created April 21, 2014 07:29
Show Gist options
  • Save rodrimaia/11135046 to your computer and use it in GitHub Desktop.
Save rodrimaia/11135046 to your computer and use it in GitHub Desktop.
Wrapper for SaveChanges adding the Validation Messages to the generated exception
/// <summary>
/// Wrapper for SaveChanges adding the Validation Messages to the generated exception
/// </summary>
/// <param name="context">The context.</param>
private void SaveChanges(DbContext context)
{
try
{
context.SaveChanges();
}
catch (DbEntityValidationException ex)
{
StringBuilder sb = new StringBuilder();
foreach (var failure in ex.EntityValidationErrors)
{
sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());
foreach (var error in failure.ValidationErrors)
{
sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
sb.AppendLine();
}
}
throw new DbEntityValidationException(
"Entity Validation Failed - errors follow:\n" +
sb.ToString(), ex
); // Add the original exception as the innerException
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment