Gil*_*rdo 3 c# entity-framework business-logic fluentvalidation asp.net-web-api
我正在构建具有以下层的应用程序
数据 - 实体框架上下文实体 - 实体框架POCO对象服务 - 由WebApi调用以加载/保存实体WebApi -
现在我相信我应该将我的业务逻辑放入服务层,因为我有实体服务,例如,我有Family对象和Family Service.
要使用FluentValidation创建验证对象,似乎必须从AbstractValidator继承,因为我的服务已经从一个对象继承这是不可能的(或者是它)?
我想我唯一的选择是在服务层创建一个FamilyValidator并从服务中调用此验证器?
fluentValidation是我最好的选择,还是我在这里混淆了什么?
Oma*_*ani 10
如果您有一个名为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;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7611 次 |
最近记录: |