【问题标题】:How to add a non-property rule in FluentValidation?如何在 FluentValidation 中添加非属性规则?
【发布时间】:2015-08-19 16:53:51
【问题描述】:

我有这个验证器类:

internal class CustomerTypeValidator : AbstractValidator<CustomerType>
{
    public CustomerTypeValidator()
    {
        RuleFor(x => x.Number).Must(BeANumber).WithState(x => CustomerTypeError.NoNumber);
    }

    private bool BeANumber(string number)
    {
        int temp;
        bool ok = int.TryParse(number, out temp);

        return ok && temp > 0;
    }
}

我有服务类:

public class CustomerTypeService
{
   public CustomerType Save(CustomerType customerType)
    {
        ValidationResult results = Validate(customerType);
        if (results != null && !results.IsValid)
        {
            throw new ValidationException<CustomerTypeError>(results.Errors);
        }

        //Save to DB here....

        return customerType;
    }

    public bool IsNumberUnique(CustomerType customerType)
    {
        var result = customerTypeRepository.SearchFor(x => x.Number == customerType.Number).Where(x => x.Id != customerType.Id).FirstOrDefault();

        return result == null;
    }

    public ValidationResult Validate(CustomerType customerType)
    {
        CustomerTypeValidator validator = new CustomerTypeValidator();
        validator.RuleFor(x => x).Must(IsNumberUnique).WithState(x => CustomerTypeError.NumberNotUnique);
        return validator.Validate(customerType);
    }
}

但是我得到以下异常:

Property name could not be automatically determined for expression x =&gt; x. Please specify either a custom property name by calling 'WithName'.

以上添加额外规则的方法不正确吗?

【问题讨论】:

  • 您找到解决问题的方法了吗?
  • @Vishal 是的。将Id 属性添加到RuleForIsNumberUnique 方法。
  • 你能发布你的答案吗?我也有同样的问题。

标签: c# fluentvalidation


【解决方案1】:

使用当前版本的 FluentValidation,可以通过以下方式解决上述问题:

public bool IsNumberUnique(CustomerType customerType, int id)
{
    var result = customerTypeRepository.SearchFor(x => x.Number == customerType.Number).Where(x => x.Id != customerType.Id).FirstOrDefault();

    return result == null;
}

public ValidationResult Validate(CustomerType customerType)
{
    CustomerTypeValidator validator = new CustomerTypeValidator();
    validator.RuleFor(x => x.Id).Must(IsNumberUnique).WithState(x => CustomerTypeError.NumberNotUnique);
    return validator.Validate(customerType);
}

【讨论】:

    猜你喜欢
    • 2013-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多