将属性名称添加到基于实体的规则?

时间:2016-05-02 14:33:20

标签: c# fluentvalidation

我有这样的规则:

RuleFor(x => x).Must(MatchSomething).When(x => x.Children != null)

private bool MatchSomething(Parent parent)
{
    return parent.CountOfSomething == parent.Children.Count(x => x.ChildType == ChildType.EnumValue);
}

以上工作正常,但根据上述规则,PropertyName的{​​{1}}为空。

有没有办法传递属性名称,还是需要更改上面的规则以使其基于属性?

1 个答案:

答案 0 :(得分:1)

Must()有一个有用的重载,我认为它可以解决你的问题,也就是说它可以包含你作为第一个参数验证的类。因此,您可以获取要显示的属性名称" CountOfSomething"使用以下代码:

class ParentValidator : AbstractValidator<Parent>
{
    public ParentValidator()
    {
        RuleFor(x => x.CountOfSomething).Must(MatchSomething).When(x => x.Children != null);
    }

    private bool MatchSomething(Parent parent, int countOfSomething)
    {
        return countOfSomething == parent.Children.Count(x => x.ChildType == ChildType.EnumValue);
    }
}

我不知道如何通过&#34; CountOfSomething&#34;作为一个参数,但上面的希望是一个非常快速的代码修复!