
我有一个用户模型,如:
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; }} 总结 以上是内存溢出为你收集整理的c# – 编写通用的FluentValidation自定义验证程序以检查唯一约束全部内容,希望文章能够帮你解决c# – 编写通用的FluentValidation自定义验证程序以检查唯一约束所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)