首页 > 解决方案 > Validator 类中的 FluentValidation 自定义函数

问题描述

使用 FluentValidation 网站上的这个示例,我使用自己的类将概念转换为 VB.NET。我的问题感兴趣的部分是Must(BeOver18)调用protected函数的 . 请注意,此调用不会将参数传递给BeOver18

public class PersonAgeValidator : AbstractValidator<Person>  {
  public PersonAgeValidator() {
    RuleFor(x => x.DateOfBirth).Must(BeOver18);
  }

  protected bool BeOver18(DateTime date) {
    //...
  }
}

我像这样在 VB.NET 中创建了自己的验证器类,使用与上面相同的主体,但使用了一个名为的函数CustomerExists

Public Class ContractValidator
    Inherits AbstractValidator(Of ContractDTO)

    Public Sub New()

        RuleSet("OnCreate",
            Sub()
                RuleFor(Function(x) x.CustomerID).NotEmpty
                ' Compiler error here:
                ' BC30455   Argument not specified for parameter 'customerID'.....
                RuleFor(Function(x) x.CustomerID).Must(CustomerExists)
            End Sub
        )

    End Sub


    Protected Function CustomerExists(customerID As Integer) As Boolean

        Return CustomerService.Exists(customerID)

    End Function

End Class

ISSUE: VB.NET 中的行.Must(CustomerExists)给出了“未为参数'customerID'指定参数...”编译器错误。C# 示例未将参数传递给BeOver18. 我尝试了一个额外的匿名内联函数来尝试传递 ContractDTO.CustomerID,但它不起作用,因为它无法识别:

' This won't work:
RuleFor(Function(x) x.CustomerID).Must(CustomerExists(Function(x) x.CustomerID))

我不知道 C# 示例如何在没有参数的情况下调用它的函数,但 VB.NET 转换不能。这是我需要帮助的地方。

标签: vb.netfluentvalidation

解决方案


您的CustomerExists函数需要被视为委托。为此,请更改以下内容:

原来的

 RuleFor(Function(x) x.CustomerID).Must(CustomerExists)

更新

RuleFor(Function(x) x.CustomerID).Must(AddressOf CustomerExists)

推荐阅读