Fel*_*ani 5 validation asp.net-mvc domain-driven-design dependency-injection fluentvalidation
我正在使用asp.net mvc 3和DDD开发一个Web应用程序.对于我的域模型验证,我一直在使用Fluent验证.这是我的第一个项目,流畅的验证,我仍然在学习和建模实体.
我的实体Customer有两个属性需要在我的系统中是唯一的,这些属性是Email和CPF(它是Brasilian文档,需要在所有系统中都是唯一的).我想知道,我怎么能这样呢?
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, ?); });
} }
Run Code Online (Sandbox Code Playgroud)
我不知道是否可能,在验证器中注入一个存储库,我怎样才能在.Must方法扩展中获取Id?或者还有另一种方法吗?
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));
Run Code Online (Sandbox Code Playgroud)
这就是说,在您尝试插入记录并捕获相应的异常而不是在验证层中执行此操作时,系统本身(数据库?)也可以更有效地检查唯一性.这样做的原因是,在您的FluentValidation检查唯一性的时间与插入记录的实际时间之间,可能会发生许多事情.
| 归档时间: |
|
| 查看次数: |
2100 次 |
| 最近记录: |