我上课了:
Sponsored { int Order };
我收藏了它:
IEnumerable<Sponsored> sponsored;
我想检查此集合中Order
是否唯一。
我可以通过FluentValidation
吗?
我有:
SponsoredValidator : AbstractValidator<IEnumerable<Sponsored>>
和
SponsoredValidator : AbstractValidator<Sponsored>
@Edit: 它应该通过ValidationAttribute
与WebAPI POST方法连接[Validator(typeof(SponsoredValidator))]
答案 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.");
}
}