Skip to content

Instantly share code, notes, and snippets.

@anthonyvscode
Last active December 31, 2015 14:08
Show Gist options
  • Save anthonyvscode/7997824 to your computer and use it in GitHub Desktop.
Save anthonyvscode/7997824 to your computer and use it in GitHub Desktop.
DbEntityValidationException with useful message returned for logging to Elmah.
Example Response Message
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. The validation errors are: [Entity: tUser, Property: CreatedBy] The CreatedBy field is required.; [Entity: tGroup, Property: CreatedBy] The CreatedBy field is required.
public void Save()
{
try
{
context.SaveChanges();
}
catch(DbEntityValidationException ex)
{
var errorMessages = (from eve in ex.EntityValidationErrors
let entity = eve.Entry.Entity.GetType().Name
from ev in eve.ValidationErrors
select new
{
Entity = entity,
PropertyName = ev.PropertyName,
ErrorMessage = ev.ErrorMessage
});
var fullErrorMessage = string.Join("; ", errorMessages.Select(e => string.Format("[Entity: {0}, Property: {1}] {2}", e.Entity, e.PropertyName, e.ErrorMessage)));
var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
}
}
@anthonyvscode
Copy link
Author

Only downside to this is that you lose your stacktrace. The plus side is, you know exactly what is failing, which I feel is far more useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment