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

标签 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
  }
}

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

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

但是,如果我不使用 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()
}

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

感谢您的宝贵时间。

最佳答案

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

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

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

关于c# - 您会在数据库调用中使用流畅的验证吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27865120/

相关文章:

asp.net-mvc - FluentValidation ShouldHaveValidationErrorFor 与 SetCollectionValidator

c# - 从 DataGrid 中自动删除新行

mongodb - Mathematica 是否支持连接到 mongo 数据库?

php - 有人知道如何通过 MYSQL 查询获取帖子图像大小吗?

python - MySQL 和 Python - 如何检查用户输入的条目?

.net - 使用嵌套验证对复杂模型进行单元测试

c# - C++ 相当于 C# 中的 new Random(seed)

c# - 2个C#进程之间进行进程间通信最简单的方法是什么?

c# - Windows 7 中菜单选项卡上的下拉按钮

c# - FluentValidation.NET 等同于 [Display(Name)]