再生产:
Imports System.ComponentModel
Imports System.ComponentModel.DataAnnotations
Module Module1
Sub Main()
Dim type = GetType(Contact)
TypeDescriptor.AddProviderTransparent(
New AssociatedMetadataTypeTypeDescriptionProvider(type), type)
Dim contact As New Contact
Dim context As New ValidationContext(contact, Nothing, Nothing)
Dim errors As New List(Of ValidationResult)
Dim result = Validator.TryValidateObject(contact, context, errors, True)
End Sub
End Module
<CustomValidation(GetType(Contact.ContactMd), "*********************")>
<MetadataType(GetType(Contact.ContactMd))>
Public Class Contact
Public Property Email As String
Public Property EmailRepeat As String
Public Class ContactMd
'<Required()>
Public Property Email
'<Required()>
Public Property EmailRepeat
Public Shared Function ValidateEmails(ByVal contact As Contact) _
As ValidationResult
Return If(contact.Email = contact.EmailRepeat,
ValidationResult.Success,
New ValidationResult("Fail!"))
End Function
End Class
End Class
上面的代码会抛出异常:
The CustomValidationAttribute method '*********************' does not exist in type 'ContactMd' or is not public and static.
这个例外是合理的,它表明一切正常。一旦我取消注释Required
Md 类中属性的属性,就不会抛出异常,这意味着验证系统不会同时验证属性类型的属性和类级别的属性。
任何解决方法?