mercredi 10 juillet 2019

For a DbEntityValidationException, how do I get the input value of the offending property?

I am handling the DbEntityValidationException as follows:

private static string HandleErrorMessages(DbEntityValidationException dbEx) { var msg = new StringBuilder();

    foreach (var validationError in dbEx.EntityValidationErrors.SelectMany(validationErrors => validationErrors.ValidationErrors))
        msg.AppendFormat("Property: {0} Error: {1}",
            validationError.PropertyName, validationError.ErrorMessage).AppendLine();

    return msg.ToString();
}

I get the error message:

Property: Phone Error: The field Phone must be a string with a maximum length of 15.

Now I want to know what is the value of Phone. How do I use reflection to get the value of the offending input? For example, I'd like to see:

Property: Phone Error: The field Phone must be a string with a maximum length of 15. User entered 'asdfasdfasdfasdfasdf'.

(I know that I need to fix my input validation, but I'd like this fallback on the back-end.)





Aucun commentaire:

Enregistrer un commentaire