DbEntityValidationException - How can I easily tell what caused the error?

c# entity-framework

Accepted Answer

The simplest answer is to overruleSaveChanges on the entities class you have. You may see theDbEntityValidationException , expose the true problems, and produce a fresh document.DbEntityValidationException with the most effective message.

  1. Next to your SomethingSomething.Context.cs file, create a partial class.
  2. Use the code found at the end of this article.
  3. I'm done now. Without requiring any refactoring, your implementation will automatically use the overridden SaveChanges.

Now, your exception message will seem as follows:

System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. The validation errors are: The field PhoneNumber must be a string or array type with a maximum length of '12'; The LastName field is required.

Any class that derives from can drop the override SaveChanges function.DbContext :

public partial class SomethingSomethingEntities
{
    public override int SaveChanges()
    {
        try
        {
            return base.SaveChanges();
        }
        catch (DbEntityValidationException ex)
        {
            // Retrieve the error messages as a list of strings.
            var errorMessages = ex.EntityValidationErrors
                    .SelectMany(x => x.ValidationErrors)
                    .Select(x => x.ErrorMessage);
    
            // Join the list to a single string.
            var fullErrorMessage = string.Join("; ", errorMessages);
    
            // Combine the original exception message with the new one.
            var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
    
            // Throw a new DbEntityValidationException with the improved exception message.
            throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
        }
    }
}

The DbEntityValidationException additionally includes the entities responsible for the validation mistakes. Therefore, you can modify the code above to produce information about these entities if you need even more details.

also see http://devillers.nl/improving-dbentityvalidationexception/

430
8/9/2014 1:47:10 AM

Popular Answer

Martin mentioned that there is additional material in theDbEntityValidationResult . I wanted to avoid having to develop custom code and found it beneficial to retrieve both my POCO class name and property name in each message.ErrorMessage qualities on all of my[Required] specific tags for this

I took care of these details by making the following modification to Martin's code:

// Retrieve the error messages as a list of strings.
List<string> errorMessages = new List<string>();
foreach (DbEntityValidationResult validationResult in ex.EntityValidationErrors)
{
    string entityName = validationResult.Entry.Entity.GetType().Name;
    foreach (DbValidationError error in validationResult.ValidationErrors)
    {
        errorMessages.Add(entityName + "." + error.PropertyName + ": " + error.ErrorMessage);
    }
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow