Wednesday, October 24, 2012

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

Issue:

While programming with Microsoft Entity Framework, you might have come across this error. The error occurs when calling the SaveChanges() method of the entity framework db context object. The original problem is not known unless you dig deeper into some of the property values of Entity Framework Exception classes.
Usually the exception raised is as below:

Server Error in '/' Application.

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

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

Solution:
You need to catch the exception (DbEntityValidationException ) and get into its properties to find the issue. Here is the catch block that will bring out the real issue:

C# Version:
catch (DbEntityValidationException dbEx)
{
    foreach (var validationErrors in dbEx.EntityValidationErrors)
    {
        foreach (var validationError in validationErrors.ValidationErrors)
        {
            Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
        }
    }
}

No comments:

Post a Comment