2011-01-20 79 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