Search code examples
.netentity-frameworkentity-framework-4.1ef-code-first

Getting exact error type in from DbValidationException


I have the situation where I'm initializing my model in DatabaseInitializer() for EF 4.1 and get this annoying error "Validation failed for one or more entities. See 'EntityValidationErrors' property for more details." So, I go to this EntityValidationErrors and there is a field {System.Data.Entity.Validation.DbEntityValidationResult} which gives me no information at all about what field it was unable to initialize. Is there a way to get more info about this error?

To clear things out:

I know how to fix the string length problem. What I'm asking is how do I get the exact field name that is breaking the model.


Solution

  • While you are in debug mode within the catch {...} block open up the "QuickWatch" window (ctrl+alt+q) and paste in there:

    ((System.Data.Entity.Validation.DbEntityValidationException)ex).EntityValidationErrors
    

    This will allow you to drill down into the ValidationErrors tree. It's the easiest way I've found to get instant insight into these errors.

    For Visual 2012+ users who care only about the first error and might not have a catch block, you can even do:

    ((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors.First().ValidationErrors.First().ErrorMessage