2016-03-22 23 views
0

Doğrulama yapılması gereken her alan için kuralların yazılmasını önlemek için bir olasılık var mıdır, örnek olarak tüm özellikler Remarks hariç doğrulanmalıdır. Ve her özellik için RuleFor yazmayı bırakmayı düşünüyordum.FluentValidation Library'yi kullanarak özelliklerde doğrulama işlemini otomatikleştirin

public class Validator<T> : AbstractValidator<T> 
{ 
    public Validator(Func<PropertyInfo, bool> filter) { 
     foreach (var propertyInfo in typeof(T) 
      .GetProperties() 
      .Where(filter)) { 
      var expression = CreateExpression(propertyInfo); 
      RuleFor(expression).NotEmpty(); 
     } 
    } 

    private Expression<Func<T, object>> CreateExpression(PropertyInfo propertyInfo) { 
     var parameter = Expression.Parameter(typeof(T), "x"); 
     var property = Expression.Property(parameter, propertyInfo); 
     var conversion = Expression.Convert(property, typeof(object)); 
     var lambda = Expression.Lambda<Func<T, object>>(conversion, parameter); 

     return lambda; 
    } 
} 

Ve gibi kullanılabilir:: Burada

public class CustomerDto 
{ 
    public int CustomerId { get; set; }   //mandatory 
    public string CustomerName { get; set; } //mandatory 
    public DateTime DateOfBirth { get; set; } //mandatory 
    public decimal Salary { get; set; }   //mandatory 
    public string Remarks { get; set; }   //optional 
} 

public class CustomerValidator : AbstractValidator<CustomerDto> 
{ 
    public CustomerValidator() 
    { 
     RuleFor(x => x.CustomerId).NotEmpty(); 
     RuleFor(x => x.CustomerName).NotEmpty(); 
     RuleFor(x => x.DateOfBirth).NotEmpty(); 
     RuleFor(x => x.Salary).NotEmpty(); 
    } 
} 
+1

Tabii – Domysee

+0

ne sıklıkla tüm özelliklerin aynı doğrulama modeli var mı? – Dennis

+0

@Domysee, lütfen bir örnek paylaşır mısınız? –

cevap

0

gitmek iyi bir başlangıç ​​olabilir yansımasını ve/veya özelliklerini kullanarak şunları yapabilirsiniz

private static void ConfigAndTestFluent() 
    { 
     CustomerDto customer = new CustomerDto(); 
     Validator<CustomerDto> validator = new Validator<CustomerDto>(x=>x.Name!="Remarks"); //we specify here the matching filter for properties 
     ValidationResult results = validator.Validate(customer); 
    } 
İlgili konular