2014-04-15 103 views
2

繼我上一個問題之後,我在我的Transaction類中有一個nullablechar,名字sourceFluent apply Rule only only if value is not null

//source isnt required but when present must be 1 character 'I' or 'M'    
    RuleFor(transaction => transaction.source.ToString()) 
     .Matches("^[IM]?$")     
     .When(t => t.source.Value != null); 

由於MatchesWhen是不可用於char,我現在用的是.ToString()方法但是,如果產生了新的Transaction對象時,源屬性爲null,應用程序失敗,因爲暫時無法轉換一個null來源到string

任何人都可以推薦一種運行驗證源的方法只有如果源不是null?我認爲我編寫的When表達式會執行此操作,並且如果源爲null,驗證過程的這一部分將被跳過,但它會嘗試處理驗證的ToString()部分,因此會導致錯誤。

+0

我編輯了自己的冠軍。請不要包含有關問題標題中使用的語言的信息,除非在沒有它的情況下沒有意義。標籤用於此目的。另請參閱[「應該在題目中包含」標籤「的問題?」](http://meta.stackexchange.com/q/19190/193440),其中的共識是「不,他們不應該。 – chridam

回答

3

MatchesWhen可用於char數據類型。

我建議這樣的事情...

public class Transaction 
{ 
    public char? source { get; set; } 
} 


public class CustomerValidator : AbstractValidator<Transaction> 
{ 
    public CustomerValidator() 
    { 
     RuleFor(t => t.source) 
      .Must(IsValidSource); 
    } 


    private bool IsValidSource(char? source) 
    { 
     if (source == 'I' || source == 'M' || source == null) 
      return true; 
     return false;      
    } 
} 
3

我不知道整個來龍去脈,但我看到一個最明顯的解決方案在這裏:

RuleFor(transaction => transaction.source != null ? transaction.source.ToString() : string.Empty) 
    .Matches("^[IM]?$")