DbEntityValidationException

When calling SaveChanges on an entity context object you can sometimes get a DbEntityValidationException error but it doesn't give you a convenient message as to what the error(s) were.  Here is a code snippet to get a convenient message from the DbEntityValidationException object:

Try 
    context.SaveChanges() 
Catch ex As DbEntityValidationException
    'Capture all default Entity Framework Validation errors like required fields, text size checks etc. 
    Dim errorMessage As New StringBuilder

    For Each validationResult As DbEntityValidationResult In ex.EntityValidationErrors
        errorMessage.AppendLine(String.Format("Entity of type [{0}] in state [{1}] has the following validation errors:",  
                                              validationResult.Entry.Entity.GetType.Name(),  
                                              validationResult.Entry.State)) 
        For Each item As DbValidationError In validationResult.ValidationErrors
            errorMessage.AppendLine(String.Format("- Property: [{0}], Error: [{1}]",  
                                                  item.PropertyName,  
                                                  item.ErrorMessage)) 
        Next 

    Next 

    Throw New DbEntityValidationException(errorMessage.ToString, ex)
End Try 

Comments

Popular posts from this blog

ToMethodObject Refactoring

How to unlock a file in Team Foundation Server(TFS)

Show/Hide formatting text in MS Word 2010