【发布时间】: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 => x. Please specify either a custom property name by calling 'WithName'.
以上添加额外规则的方法不正确吗?
【问题讨论】:
-
您找到解决问题的方法了吗?
-
@Vishal 是的。将
Id属性添加到RuleFor和IsNumberUnique方法。 -
你能发布你的答案吗?我也有同样的问题。
标签: c# fluentvalidation