Created
April 21, 2014 07:29
-
-
Save rodrimaia/11135046 to your computer and use it in GitHub Desktop.
Wrapper for SaveChanges adding the Validation Messages to the generated exception
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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