5

我正在使用 asp.net mvc 3 和 DDD 开发一个 Web 应用程序。对于我的域模型验证,我一直在使用 Fluent Validation。这是我的第一个流利验证项目,我仍在学习和建模实体。

我的实体 Customer 有两个属性需要在我的系统中唯一,这些属性是 Email 和 CPF(它是巴西文档,需要在所有系统中唯一)。我想知道,我该怎么做呢?

Soo,我的想法是,在我的 Customer 验证类中注入(通过构造函数)我的存储库,并通过自定义验证对其进行检查。验证将使用存储库检查,如果我的表中有记录,此电子邮件的 ID 不同(0 表示插入,真实 ID 表示更新......我不需要检查我正在更新的记录,因为它' d 总是正确的)。

我正在尝试这样的事情:

 public class CustomerValidator : AbstractValidator<Customer> {

     protected ICustomerRepository Repository { get; set; }

     // I intend to inject it by IoC with Unity.. is it possible ?
     public CustomerValidator(ICustomerRepository rep) 
     {
         this.Repository = rep;

         // other properties

         RuleFor(customer = customer.Email)
             .EmailAddress()
             .NotEmpty()
             .Must(email = { return Repository.IsEmailInUse(email, ?); });

         RuleFor(customer = customer.CPF)
             .NotEmpty()
             .Must(cpf = { return Repository.IsCPFInUse(cpf, ?); });

     }   }

我不知道是否有可能,在验证器中注入一个存储库,以及如何在 .Must 方法扩展中获取 Id ?还是有其他方法可以做到这一点?

4

1 回答 1

9
RuleFor(customer => customer.Email)
    .EmailAddress()
    .NotEmpty()
    .Must((customer, email) => Repository.IsEmailInUse(email, customer.Id));

RuleFor(customer => customer.CPF)
    .NotEmpty()
    .Must((customer, cpf) => Repository.IsCPFInUse(cpf, customer.Id));

话虽如此,当您尝试插入记录并捕获适当的异常而不是在验证层中执行此操作时,系统本身(数据库?)也可以更有效地检查唯一性。原因是在 FluentValidation 检查唯一性和插入记录的实际时间之间可能会发生很多事情。

于 2011-07-19T05:23:07.400 回答