在 Fluentvalidation 中使用 SetValidator 验证通用集合

问题描述 投票:0回答:1

我正在尝试验证通用类型:

public class Request<T> where T : class
{
    public int Test { get; set; }

    public List<T> Records { get; set; } = [];
}

如何设置

SetValidator
?我遇到错误:
Cannot convert from ‘QuotasValidator’ to ‘FluentValidation.Validators.IPropertyValidator<Request<T>, T>’
。我也试过
RuleForEach(request => request.Records.OfType<Quotas>()).SetValidator(new QuotasValidator());

public class RequestValidator<T> : AbstractValidator<Request<T>> where T : class
{
    public RequestValidator()
    {
        //if (T is typeOf(..))
            RuleForEach(request => request.Records).SetValidator<T>(new QuotasValidator());
    }
}

是否有可用的现成解决方案,或者我是否需要实施自定义解决方案?我查看了多态验证器。也许我缺少一种方法?

c# fluentvalidation
1个回答
-1
投票

我最终使用了多态验证器:

public interface IRequest<T>
{
    public List<T> Records { get; set; }
}

public class QuotaRequest : IRequest<Item>
{
    public List<Item> Records { get; set; } = [];
}

public class RequestValidator : AbstractValidator<QuotaRequest>
{
    public RequestValidator()
    {
        RuleForEach(request => request.Records).SetValidator(new ItemValidator());
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.