使用属性上的sum验证集合

时间:2015-05-28 11:56:25

标签: c# fluentvalidation

我有这两个实体:

public class Parent
{
    public ICollection<Child> Children {get; set;}
}

public class Child
{
    public decimal Percentage {get; set;}
}

我想添加验证规则,以便所有孩子的总Percentage为100.如何在以下验证器中添加此规则?

public ParentValidator()
{
    RuleFor(x => x.Children).SetCollectionValidator(new ChildValidator());
}

private class ChildValidator : AbstractValidator<Child>
{
    public ChildValidator()
    {
        RuleFor(x => x.Percentage).GreaterThan(0));
    }
}

1 个答案:

答案 0 :(得分:3)

对集合属性使用谓词验证器:

public class ParentValidator : AbstractValidator<Parent> 
{
    public ParentValidator()
    {
        RuleFor(x => x.Children)
            .SetCollectionValidator(new ChildValidator())
            .Must(coll => coll.Sum(item => item.Percentage) == 100);
    }
}