gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:46:37 25 4
gpt4 key购买 nike

通过流畅的验证,您可以在更新密码之前验证简单的事情,例如 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com