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

3

我有这个验证器类:

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

但是我遇到了以下异常:

属性名称无法自动确定表达式x => x的属性名称。 请通过调用'WithName'指定自定义属性名称。

上述方式添加额外规则不正确吗?


你找到解决问题的方法了吗? - Vishal
@Vishal 是的。已经在 RuleFor 中添加了 Id 属性和 IsNumberUnique 方法。 - Ivan-Mark Debono
你能发表你的答案吗?我遇到了同样的问题。 - Vishal
1个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接