如何在 FluentValidation 中添加非 属性 规则?

How to add a non-property rule in FluentValidation?

我有这个验证器 class:

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;
    }
}

我有服务 class:

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 => x. Please specify either a custom property name by calling 'WithName'.

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

使用当前版本的 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);
}