您会在数据库调用中使用流畅的验证吗

Azr*_*ran 5 c# database fluentvalidation

通过流畅的验证,您可以在更新密码之前验证简单的内容,例如 NotNull 、 numberGreaterThan 或更高级的业务规则(例如 userMustExistsOnDb )。

我觉得当我使用流畅验证时,我执行的数据库调用次数是不使用它时的两倍。这是一个例子。

public class DeleteCustomerRequestValidator: AbstractValidator<DeleteCustomerRequest> {
  public DeleteCUstomerRequestValidator() {
    RuleFor(customer => customer.Id).GreaterThan(0);
    RuleFor(customer => customer.Id).Must(ExistsOnDB).WithMessage("The customer does not exists");
  }

  private bool ExistsOnDB(int customerId) {
    // DB call to check if exists on Db
    return Respository.Customers.Any(x => x.Id == customerId)    // CALL NUMBER 1
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我进行第二次调用的删除方法

public void DeleteCustomer(int customerId)
{
     Customer customer = Repository.Customers.First(x => x.Id);  // CALL NUMBER 2
     Repository.Customers.Delete(customer) 
     Repository.Save()
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我不使用 Fluent 验证,我将只进行一次调用来从数据库获取客户。

public void DeleteCustomer(int customerId)
{
     if (customerId < 1)
     {
         /// Return error.
     }
     Customer customer = Repository.Customers.FirstOrDefault(x => x.Id);  // Only 1 CALL
     if (customer == null)
     {
         // Return error.
     }
     Repository.Customers.Delete(customer) 
     Repository.Save()
}
Run Code Online (Sandbox Code Playgroud)

我做错了什么?有更好的方法吗?

谢谢你的时间。

hat*_*cyl 1

一般来说,我会说不,不要使用 Fluent Validation。

  1. 我认为您正在添加额外的复杂性/不必要的 AbstractValidator 类,其中一个简单的 if 就足够了。

  2. 对于“删除”之类的内容,是的,您将首先检查客户是否存在。但大部分逻辑应该位于 Customer 类本身中。因此,您不需要这个外部验证器类。