gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:09:05 26 4
gpt4 key购买 nike

我有这个验证器类:

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”指定自定义属性名称。

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

最佳答案

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

关于c# - 如何在 FluentValidation 中添加非属性规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28187392/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com