2011-01-20 99 views
19

我使用了Fluent验证器。但有时我需要创建一个规则层次结构。例如:流利的验证。继承验证类

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

我想继承从UserValidation到RootValidation的验证规则。但是这段代码没有工作:

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抽象。但它已经很棒了!谢谢! – 2016-03-08 12:06:17