如何在c#应用程序中使用FluentValidation

时间:2014-10-21 12:12:55

标签: c# entity-framework asp.net-web-api business-logic fluentvalidation

我正在构建具有以下图层的应用程序

数据 - 实体框架上下文 实体 - 实体框架POCO对象 服务 - 由WebApi调用以加载/保存实体 WebApi -

现在我相信我应该将我的业务逻辑放入服务层,因为我有实体服务,例如,我有Family对象和Family Service。

要使用FluentValidation创建验证对象,似乎必须从AbstractValidator继承,因为我的服务已经从一个对象继承这是不可能的(或者是它)?

我想我唯一的选择是在服务层创建一个FamilyValidator并从服务中调用此验证器?

fluentValidation是我最好的选择,还是我在这里混淆了什么?

1 个答案:

答案 0 :(得分: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;