How to validate collection items using RuleForEach

时间:2018-08-22 13:51:24

标签: c# fluentvalidation

I have been using (successfully) the following validation:

RuleFor(x => x.Items)
  .SetCollectionValidator(new ItemValidator())
  .Must(coll => coll.Sum(item => item.Percentage) == 100)
  .When(x => x.Items != null);

As the above SetCollectionValidator is (will be) deprecated, I changed it to:

RuleForEach(x => x.Items)
  .SetValidator(new ItemValidator())
  .Must(coll => coll.Sum(item => item.Percentage) == 100)
  .When(x => x.Items != null);

However, Sum is not recognized anymore.

How can I fix this?

1 个答案:

答案 0 :(得分:1)

您可以使用两个单独的规则。其中之一是验证项目,另一项是用于验证集合。

RuleForEach(x => x.Items)
  .SetValidator(new ItemValidator());

RuleFor(x => x.Items)
  .Must(coll => coll.Sum(item => item.Percentage) == 100)
  .When(x => x.Items != null);