Skip to content

Instantly share code, notes, and snippets.

@tiesont
Last active March 12, 2017 22:54
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 tiesont/7d68be60b5d4d2e8d4265f1730e57f22 to your computer and use it in GitHub Desktop.
Save tiesont/7d68be60b5d4d2e8d4265f1730e57f22 to your computer and use it in GitHub Desktop.
Partial class, with overrrides for the various overloads of DbContext.SaveChanges, for getting the inner exceptions from a "DbEntityValidationException" event. Change "DataModel" to the name you gave your data model.
public partial class DataModel
{
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (DbEntityValidationException ex)
{
string exceptionMessage = GenerateVerboseExceptionMessage(ex);
// Throw a new DbEntityValidationException with the improved exception message.
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors, ex.InnerException);
}
}
public override Task<int> SaveChangesAsync()
{
try
{
return base.SaveChangesAsync();
}
catch (DbEntityValidationException ex)
{
string exceptionMessage = GenerateVerboseExceptionMessage(ex);
// Throw a new DbEntityValidationException with the improved exception message.
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors, ex.InnerException);
}
}
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken)
{
try
{
return base.SaveChangesAsync(cancellationToken);
}
catch (DbEntityValidationException ex)
{
string exceptionMessage = GenerateVerboseExceptionMessage(ex);
// Throw a new DbEntityValidationException with the improved exception message.
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors, ex.InnerException);
}
}
private string GenerateVerboseExceptionMessage(DbEntityValidationException ex)
{
var errorMessages = new List<string>();
foreach (var validationResult in ex.EntityValidationErrors)
{
string entityName = validationResult.Entry.Entity.GetType().Name;
foreach (var error in validationResult.ValidationErrors)
{
errorMessages.Add(entityName + "." + error.PropertyName + ": " + error.ErrorMessage);
}
}
// Join the list to a single string.
var fullErrorMessage = string.Join(Environment.NewLine, errorMessages);
return string.Concat(ex.Message, " The validation errors are: ", Environment.NewLine, fullErrorMessage);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment