加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 07:52:12 所属栏目:百科 来源:网络整理
导读:对C#,ASP.NET MVC和FluentValidation来说真的很新. 我有一个用户模型,如: public class UserDetails{ public int ID { get; set; } public string UserName { get; set; } public string Email { get; set; }} 现在,我一直在使用FluentValidation验证UserNa
对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;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读