Last active
June 8, 2018 10:11
-
-
Save 0xced/a17c245bd87258390dd87b6c94875247 to your computer and use it in GitHub Desktop.
Improved DbEntityValidationException message
This file contains 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
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