FluentValidation和对象的集合,其属性应该是唯一的

时间:2017-06-20 09:23:48

标签: c# fluentvalidation

我上课了:

Sponsored { int Order };

我收藏了它:

IEnumerable<Sponsored> sponsored; 

我想检查此集合中Order是否唯一。

我可以通过FluentValidation吗?

我有:

SponsoredValidator : AbstractValidator<IEnumerable<Sponsored>>

SponsoredValidator : AbstractValidator<Sponsored>

@Edit: 它应该通过ValidationAttribute

与WebAPI POST方法连接
[Validator(typeof(SponsoredValidator))]

1 个答案:

答案 0 :(得分:1)

public class SponsoredCollectionValidator : AbstractValidator<IEnumerable<Sponsored>>
{
    private class SponsoredComparer : IEqualityComparer<Sponsored>
    {
        public bool Equals(Sponsored x, Sponsored y) => x?.Order == y?.Order;
        public int GetHashCode(Sponsored obj) => obj.Order;
    }

    public SponsoredCollectionValidator()
    {
       RuleFor(coll => coll)
           .Must(coll => coll.Distinct(new SponsoredComparer()).Count() == coll.Count())
           .WithMessage("Elements are not unique.");
    }
}