2011-01-20 13 views
19

मैंने फ्लुएंट वैलिडेटर का उपयोग किया। लेकिन कभी-कभी मुझे नियमों का पदानुक्रम बनाना पड़ता है। उदाहरण के लिए:फ्लुएंट मान्यताओं। इनहेरिट सत्यापन वर्ग

[Validator(typeof(UserValidation))] 
public class UserViewModel 
{ 
    public string FirstName; 
    public string LastName; 
} 

public class UserValidation : AbstractValidator<UserViewModel> 
{ 
    public UserValidation() 
    { 
     this.RuleFor(x => x.FirstName).NotNull(); 
     this.RuleFor(x => x.FirstName).NotEmpty(); 

     this.RuleFor(x => x.LastName).NotNull(); 
     this.RuleFor(x => x.LastName).NotEmpty(); 
    } 
} 

public class RootViewModel : UserViewModel 
{ 
    public string MiddleName;  
} 

मैं उपयोगकर्ता सत्यापन से रूट प्रमाणीकरण के सत्यापन नियमों का उत्तराधिकारी बनाना चाहता हूं। लेकिन इस कोड काम नहीं किया:

public class RootViewModelValidation:UserValidation<RootViewModel> 
{ 
    public RootViewModelValidation() 
    { 
     this.RuleFor(x => x.MiddleName).NotNull(); 
     this.RuleFor(x => x.MiddleName).NotEmpty(); 
    } 
} 

मैं सत्यापन वर्ग कैसे वारिस कर सकते हैं FluentValidation का उपयोग कर?

उत्तर

29

इसे हल करने के लिए, आपको UserValidation कक्षा सामान्य में बदलनी होगी। नीचे कोड देखें।

public class UserValidation<T> : AbstractValidator<T> where T : UserViewModel 
{ 
    public UserValidation() 
    { 
     this.RuleFor(x => x.FirstName).NotNull(); 
     this.RuleFor(x => x.FirstName).NotEmpty(); 

     this.RuleFor(x => x.LastName).NotNull(); 
     this.RuleFor(x => x.LastName).NotEmpty(); 
    } 
} 

[Validator(typeof(UserValidation<UserViewModel>))] 
public class UserViewModel 
{ 
    public string FirstName; 
    public string LastName; 
} 

public class RootViewModelValidation : UserValidation<RootViewModel> 
{ 
    public RootViewModelValidation() 
    { 
     this.RuleFor(x => x.MiddleName).NotNull(); 
     this.RuleFor(x => x.MiddleName).NotEmpty(); 
    } 
} 

[Validator(typeof(RootViewModelValidation))] 
public class RootViewModel : UserViewModel 
{ 
    public string MiddleName; 
} 
+0

मैं व्यक्तिगत रूप से UserValidation सार बनाने की कोशिश करता हूं। लेकिन यह पहले से ही महान है! धन्यवाद! –

संबंधित मुद्दे