EntityValidationErrors in Entity Framework

After executing an Entity Framework query, I received the following error:
Validation failed for one or more entities. See ‘EntityValidationErrors’ property for more details.

This is a very generic exception that didn’t gave me a clue what the problem was. I following a recommendation to add an exception handler for type DbEntityValidationException.
This exception revealed the true cause of the problem: I had mistakenly restricted the length of a varchar field to 30 and tried to insert a value of length 38 via Entity Framework.

catch (DbEntityValidationException dbEx)
{
string detailedException = “”;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
detailedException = detailedException + validationError.ErrorMessage + “; “;
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *