Getting exact error type in from DbValidationException

后端 未结 6 1048
闹比i
闹比i 2020-12-02 03:24

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

6条回答
  •  隐瞒了意图╮
    2020-12-02 03:48

    I found it useful to create a SaveChanges wrapper which makes the EntityValidationErrors more readable:

    Public Sub SaveChanges(entities As Entities)
    
        Try
            entities.SaveChanges()
    
        Catch ex As DbEntityValidationException
    
            Dim msg As New StringBuilder
            msg.AppendLine(ex.Message)
    
            For Each vr As DbEntityValidationResult In ex.EntityValidationErrors
                For Each ve As DbValidationError In vr.ValidationErrors
                    msg.AppendLine(String.Format("{0}: {1}", ve.PropertyName, ve.ErrorMessage))
                Next
            Next
    
            Throw New DbEntityValidationException(msg.ToString, ex.EntityValidationErrors, ex)
    
        End Try
    
    End Sub
    

    and then changed 'entities.SaveChanges()' to 'SaveChanges(entities)' in my entire project

提交回复
热议问题