2014-04-15 56 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]?$")