我正在构建具有以下层的应用程序
数据-实体框架上下文实体-实体框架POCO对象服务-由WebApi调用以加载/保存实体WebApi-
现在,我认为我应该将业务逻辑放入服务层,因为我有针对实体的服务,例如,我有家庭对象和家庭服务。
要使用FluentValidation创建一个验证对象,您似乎必须从AbstractValidator继承,因为我的服务已经从一个对象继承了,这是不可能的吗?
我猜我唯一的选择是在服务层中创建FamilyValidator并从服务中调用此验证器?
fluentValidation是我最好的选择,还是我在这里感到困惑?
如果您有一个名为Customer的实体,这就是您为其编写验证器的方式:
public class CustomerValidator: AbstractValidator<Customer> {
public CustomerValidator() {
RuleFor(customer => customer.Surname).NotEmpty();
RuleFor(customer => customer.Forename).NotEmpty().WithMessage("Please specify a first name");
RuleFor(customer => customer.Discount).NotEqual(0).When(customer => customer.HasDiscount);
RuleFor(customer => customer.Address).Length(20, 250);
RuleFor(customer => customer.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");
}
private bool BeAValidPostcode(string postcode) {
// custom postcode validating logic goes here
}
}
Customer customer = new Customer();
CustomerValidator validator = new CustomerValidator();
ValidationResult results = validator.Validate(customer);
bool validationSucceeded = results.IsValid;
IList<ValidationFailure> failures = results.Errors;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句