Last active
December 31, 2015 14:08
-
-
Save anthonyvscode/7997824 to your computer and use it in GitHub Desktop.
DbEntityValidationException with useful message returned for logging to Elmah.
This file contains hidden or 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
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. |
This file contains hidden or 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 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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.