Last active
March 12, 2017 22:54
-
-
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.
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 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