0

我目前正在研究用VB.NET編寫的Winforms應用程序並實現實體框架(4.4)。我想爲我的實體添加驗證屬性,以便我可以在UI上驗證它們 - 就像我在MVC中一樣。僅應用第一個DataAnnotation驗證

我創建了我的'Buddy Class',其中包含一個IsValid方法並指向包含數據註釋的'MetaData'類。 進口System.ComponentModel.DataAnnotations 進口System.Runtime.Serialization 進口System.ComponentModel

<MetadataTypeAttribute(GetType(ProductMetadata))> 
Public Class Product 

    Private _validationResults As New List(Of ValidationResult) 
    Public ReadOnly Property ValidationResults() As List(Of ValidationResult) 
     Get 
     Return _validationResults 
    End Get 
End Property 

Public Function IsValid() As Boolean 

    TypeDescriptor.AddProviderTransparent(New AssociatedMetadataTypeTypeDescriptionProvider(GetType(Product), GetType(ProductMetadata)), GetType(Product)) 

    Dim result As Boolean = True 

    Dim context = New ValidationContext(Me, Nothing, Nothing) 

    Dim validation = Validator.TryValidateObject(Me, context, _validationResults) 

    If Not validation Then 
     result = False 
    End If 

    Return result 

End Function 

End Class 

Friend NotInheritable Class ProductMetadata 

    <Required(ErrorMessage:="Product Name is Required", AllowEmptyStrings:=False)> 
    <MaxLength(50, ErrorMessage:="Too Long")> 
    Public Property ProductName() As Global.System.String 

    <Required(ErrorMessage:="Description is Required")> 
    <MinLength(20, ErrorMessage:="Description must be at least 20 characters")> 
    <MaxLength(60, ErrorMessage:="Description must not exceed 60 characters")> 
    Public Property ShortDescription As Global.System.String 

    <Required(ErrorMessage:="Notes are Required")> 
    <MinLength(20, ErrorMessage:="Notes must be at least 20 characters")> 
    <MaxLength(1000, ErrorMessage:="Notes must not exceed 1000 characters")> 
    Public Property Notes As Global.System.String 

End Class 

在IsValid的方法的第一行將元數據註冊類(只有這樣,我能找到的實際工作 - 否則,沒有註釋很榮幸!)。然後我使用System.ComponentModel.Validator.TryValidateObject方法來執行驗證。

當我調用具有空(空/無)ProductName的實例的IsValid方法時,驗證失敗,並且ValidationResults集合填充了正確的錯誤消息。到目前爲止這麼好.....

但是,如果我在一個ProductName長度超過50個字符的實例上調用IsValid,儘管有MaxLength屬性,驗證仍然通過!另外,如果我對具有有效ProductName(不是空且不超過50個字符)但沒有ShortDescription的實例調用IsValid,即使該屬性上存在必需的註釋,驗證也會通過。

我在這裏做錯了什麼?

回答

2

嘗試其他方法簽名TryValidateObject()並明確設置validateAllProperties爲true:

Dim validation = Validator.TryValidateObject(
     Me, context, _validationResults, true) 
+1

自我提醒 - 經常檢查過載!謝謝@qujck :-) – DilbertDave

+0

@DilbertDave TBH我不明白爲什麼有一個方法版本只做一些檢查! – qujck

+0

我既不 - 也許是一個功能;-) – DilbertDave

相關問題