对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; } }