System.Data.Entity.Validation.DbEntityValidationResult – Validation failed for one or more entities. See ‘EntityValidationErrors’ property for more details.

While working with Entity Framework 5.x I came across the following error:

“Validation failed for one or more entities. See ‘EntityValidationErrors’ property for more details.”

The description by itself is not helpful at all. It doesn’t tell you the exact cause of the problem. The exception is usually thrown when dbContext.SaveChanges() method is called.

I used database first approach and defined a table Car with following fields:

  • CarId (int: primary key [auto increment])
  • Brand (varchar [required])
  • Model (varchar [required])
  • Description (varchar)
  • Region (varchar [required])

I then wrote the following code:

using (var dbContext = new SampleDBEntities())
  var car = new Car()
    Brand = “BMW”,
    Model = “2012”,
    Description = “car description”

You can see that required field Region is missing from the car object initializer. When I tried to save changes the system rejects the request and throws an exception because it cannot store null for that property. The exception doesn’t tell the exact reason.

In order to find the culprit, wrap dbContext.SaveChanges() in try/catch block. Write each property to console along with its descrition as shown in the code below. The information written to the console is a lot more helpful then standard exception description.

catch (DbEntityValidationException ex)
  foreach (var entityValidationErrors in ex.EntityValidationErrors)
    foreach (var validationError in entityValidationErrors.ValidationErrors)
      Console.WriteLine(“Property: {0} Error: {1}”,
        validationError.PropertyName,validationError.ErrorMessage);                 }

Note: Use this approach only in the debug mode and remove try/catch in order to make sure that you don’t lose exception thrown in the live environment.

This entry was posted in .NET C#, Entity Framework and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s