FluentValidation 如何验证孙子

FluentValidation how to validate grandchild

以下是我的 3 级 class(员工 > 项目 > 队友)。我能够验证子项(项目)的状态,其中仅当项目列表不为空时才进行验证。

但是在 Teammate 级别,我不知道如何检查 TeamateName 属性。基本上我想对孙子做同样的事情,如果有队友,请确保检查 teammateName 是否为空或 null。

谢谢!

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }        

    public List<ProjectsDto> Projects { get; set; }
}

public class ProjectsDto
{
    public string Status { get; set; }
      
    public List<TeammatesDto> Teammates { get; set; }
}

public class TeammatesDto
{
    public string TeammateName { get; set; }
    public string PreviousProject { get; set; }
}

public class CreateEmployeeCommandValidator : AbstractValidator<CreateEmployeeCommand>
{
    private readonly IApplicationDbContext _context;

    public CreateEmployeeCommandValidator(IApplicationDbContext context)
    {
        _context = context;         

        RuleFor(v => v.Name)
            .NotEmpty().WithMessage("Name is required.")
            .MaximumLength(30).WithMessage("Name must not exceed 30 characters.");

        RuleFor(v => v.Projects)
            .ForEach(projectRule => {
                projectRule.Must(item => item.Status == null).WithMessage("Status is required");
            })
       .When(v => !StringUtil.IsNullOrEmptyList(v.Projects));

    }

我认为最好和更有条理的选择是使用 SetValidator,你可以在 foreach 规则中使用,或者只用于子对象,所以代码将是这样的:


        RuleFor(v => v.Name)
            .NotEmpty()
                .WithMessage("Name is required.")
            .MaximumLength(30)
                .WithMessage("Name must not exceed 30 characters.");

        RuleForEach(v => v.Projects)
            .SetValidator(new YourProjectsValidator());

在 YourProjectsValidator 中,您将像这样调用 Teammates 验证器:

RuleForEach(v => v.Teammates)
            .SetValidator(new YourTeammatesValidator());