c# – 编写通用的FluentValidation自定义验证程序以检查唯一约束

对C#,ASP.NET MVC和FluentValidation来说真的很新.

我有一个用户模型,如:

public class UserDetails{
    public int ID { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
}

现在,我一直在使用FluentValidation验证UserName和Email,例如:

public AdminDetailsValidator(){
        RuleFor(ad => ad.UserName).NotNull().Must(UniqueUserName(UserName)).WithMessage("UserName not Available");
        RuleFor(ad => ad.Email).NotNull().Must(UniqueEmail(Email)).WithMessage("This Email id has already been registered"); ;
    }

    public bool UniqueUserName(string un)
    {
        if (UserDbContext.userDetails.SingleOrDefault(p => p.UserName == un) == null)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public bool UniqueEmail(string em)
    {
        if (UserDbContext.userDetails.SingleOrDefault(p => p.Email == em) == null)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

但我宁愿想要一个更通用的UniqueValidator,我可以使用多个类和属性.或者至少,我不必为每个房产单独设置一个功能.所以我查看了自定义验证器.但我不知道,我如何使用该功能满足我的需求.
我想做这样的事情:

RuleFor(ad => ad.Email).NotNull().SetValidator(new UniquePropertyValidator<UserDbContext>(userDetails.Email).WithMessage("This Email id has already been registered");

甚至可以这样做吗?我想传递DbContext作为类型参数和属性作为参数(或它的一些变体,无论哪个工作).并且该方法可以针对表检查属性并返回它是否唯一.

解决方法

你有没有考虑过使用lambdas和泛型?我没有使用FluentValidation,因此这可能不是验证器的正确方法.
var dbContext = new UserDbContext();
RuleFor(ud => ud.Email)
    .NotNull()
    .SetValidator(
        new UniquePropertyValidator<UserDetails>
         (ud,ud => ud.Email,() => dbcontext.userDetails)
    .WithMessage("This Email id has already been registered");

public class UniquePropertyValidator<T> {
    public UniquePropertyValidator(T entity,Func<T,string> propertyAccessorFunc,Func<IEnumerable<T>> collectionAccessorFunc) {
        _entity = entity;
        _propertyAccessorFunc =  propertyAccessorFunc;
        _collectionAccessorFunc =collectionAccessorFunc;
    }

    public bool Validate(){
       //Get all the entities by executing the lambda
       var entities = _collectionAccessorFunc();

       //Get the value of the entity that we are validating by executing the lambda
       var propertyValue = _propertyAccessorFunc(_entity);

       //Find the matching entity by executing the propertyAccessorFunc against the 
       //entities in the collection and comparing that with the result of the entity 
       //that is being validated. Warning SingleOrDefault will throw an exception if
       //multiple items match the supplied predicate
       //http://msdn.microsoft.com/en-us/library/vstudio/bb342451%28v=vs.100%29.aspx
       var matchingEntity = entities.SingleOrDefault(e => _propertyAccessorFunc(e) == propertyValue);
       return matchingEntity == null;
    }
}

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...