Skip to content

Instantly share code, notes, and snippets.

@0xced
Last active June 8, 2018 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0xced/a17c245bd87258390dd87b6c94875247 to your computer and use it in GitHub Desktop.
Save 0xced/a17c245bd87258390dd87b6c94875247 to your computer and use it in GitHub Desktop.
Improved DbEntityValidationException message
public partial class MyContext
{
// Adapted from https://blogs.infosupport.com/improving-dbentityvalidationexception/
public override Task<int> SaveChangesAsync()
{
try
{
return base.SaveChangesAsync();
}
catch (DbEntityValidationException exception)
{
var errorMessage = new StringBuilder();
foreach (var validationError in exception.EntityValidationErrors)
{
errorMessage.AppendLine($"* {validationError.Entry.Entity.GetType().FullName} ({validationError.Entry.State})");
foreach (var error in validationError.ValidationErrors)
{
errorMessage.AppendLine($" - {error.ErrorMessage}");
}
}
var entityCount = exception.EntityValidationErrors.Count();
var entity = entityCount == 1 ? "entity" : "entities";
throw new DbEntityValidationException($"Validation failed for {entityCount} {entity}. See below for more details." + Environment.NewLine + errorMessage, exception.EntityValidationErrors);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment