0

再生产:

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.

这个例外是合理的,它表明一切正常。一旦我取消注释RequiredMd 类中属性的属性,就不会抛出异常,这意味着验证系统不会同时验证属性类型的属性和类级别的属性。

任何解决方法?

4

2 回答 2

0

答案是,验证系统首先验证属性验证属性(本例中的属性),并且仅在对象通过属性属性Required时才会继续。CustomValidationAttribute

所以根据上面的复制,改变线

Dim contact As New Contact

类似于(允许实体通过属性验证):

Dim contact As New Contact With { .Email = "*", .EmailRepeat = "*" }

将抛出预期的异常。

于 2011-04-06T07:44:45.160 回答
0

CustomValidationAttribute 指定的方法的签名必须是:

VB:

Public Shared Function OnValidate(
    entity As Contact, context As ValidationContext) As ValidationResult

C#:

public static ValidationResult OnValidate(Contact entity, ValidationContext context)

如果验证成功,它应该返回 ValidationResult.Success。

于 2011-05-17T21:19:52.743 回答