Entity Framework DbEntityValidationException

Problem

When Entity Framework attempts to save an entity and the validation fails, SaveChanges() will throw a generic DbEntityValidationException.

The exception doesn’t specify the actual validation errors, making the troubleshooting process difficult.

System.Data.Entity.Validation.DbEntityValidationException:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

Solution

We can configure KissLog to capture and log the Entity Framework validation errors.

Appending ValidationErrors to the log message
DbEntityValidationException:
Field: ProductCode, Error: The field ProductCode must be a string or array type with a maximum length of '8'.
Field: Description, Error: The Description field is required.

Implementation

Global.asax
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
namespace MyApp.Mvc
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            // [...]

            ConfigureKissLog();
        }

        private void ConfigureKissLog()
        {
            KissLogConfiguration.Options
                .AppendExceptionDetails((Exception ex) =>
                {
                    StringBuilder sb = new StringBuilder();

                    if (ex is DbEntityValidationException dbException)
                    {
                        sb.AppendLine("DbEntityValidationException:");

                        foreach (var error in dbException.EntityValidationErrors.SelectMany(p => p.ValidationErrors))
                        {
                            string message = string.Format("Field: {0}, Error: {1}", error.PropertyName, error.ErrorMessage);
                            sb.AppendLine(message);
                        }
                    }

                    return sb.ToString();
                });
        }
    }
}