Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save feliperomero3/849331001c9cef325b2537432ab04319 to your computer and use it in GitHub Desktop.
Save feliperomero3/849331001c9cef325b2537432ab04319 to your computer and use it in GitHub Desktop.
Display all entity validation errors (EF 6)
public class ApplicationDbContext : DbContext
{
//...
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (DbEntityValidationException e)
{
ThrowEnhancedValidationException(e);
}
return 0;
}
public override Task<int> SaveChangesAsync()
{
try
{
return base.SaveChangesAsync();
}
catch (DbEntityValidationException e)
{
ThrowEnhancedValidationException(e);
}
return Task.FromResult(0);
}
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken)
{
try
{
return base.SaveChangesAsync(cancellationToken);
}
catch (DbEntityValidationException e)
{
ThrowEnhancedValidationException(e);
}
return Task.FromResult(0);
}
protected virtual void ThrowEnhancedValidationException(DbEntityValidationException e)
{
var errorMessages = e.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
var fullErrorMessage = string.Join("; ", errorMessages);
var exceptionMessage = string.Concat(e.Message, " The validation errors are: ", fullErrorMessage);
throw new DbEntityValidationException(exceptionMessage, e.EntityValidationErrors);
}
}
try
{
_db.SaveChanges();
}
catch (DbEntityValidationException ex)
{
foreach (var eve in ex.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
}
try
{
_db.SaveChangesAsync();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
System.Diagnostics.Debug.Print("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
System.Diagnostics.Debug.Print("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment