How to validate collection items using RuleForEach

纵然是瞬间 提交于 2019-12-23 12:17:37

问题


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:


You can use two separate rules. One of them is validate item, and other one is for validation of collection.

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

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


来源:https://stackoverflow.com/questions/51968442/how-to-validate-collection-items-using-ruleforeach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!