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

时间:2015-01-28 08:07:30

标签: c# fluentvalidation

我有这个验证器类:

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

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

1 个答案:

答案 0 :(得分:3)

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