2016-04-08 40 views
2

我有一個源對象,從它的System.Data.DataRow字符串屬性派生將拋出異常獲取如果基礎值爲DBNull的AutoMapper獲取拋出異常的屬性時如何忽略異常?

private static void CreateMappings(IMapperConfiguration config) 
{ 
    config.CreateMap<SrcRow, DestDto>() 
    .ForMember(d => d.Error_Text, opt => opt.ResolveUsing(row => 
     { 
      try 
      { 
       // the getter of this string property throws exception if internal value is DBNull 
       return row.error_text; 
      } 
      catch 
      { 
       return null; 
      } 
     })) 
    ; 

}

所有的源和目標屬性字符串。源對象是DataRow的包裝器,每個屬性都獲取特定的行值。如果行值爲DBNull值,則屬性getter將引發異常。我怎樣才能實現這個代碼,但爲所有目標類型的成員,而不是複製/粘貼這個代碼爲每個成員?要做到這一點

+1

不要將異常用作控制流。您可以輕鬆將其轉換爲條件回報。 –

+0

即使我嘗試: var x = row.error_text; 它仍然會拋出。我必須趕上。這不是我可以檢查的字段: if(row.error_text == null) – Vince

+0

屬性看起來像這樣: public string error_text { get {//如果基礎值是DBNull,則拋出新的Exception()} 設置{} } – Vince

回答

0

一種方法是使用ForAllMembers()方法和創造條件的值映射只有當源不拋出異常:

config.CreateMap<SrcRow, DestDto>().ForAllMembers(opts => opts.Condition(rc => 
{ 
    try { return rc.SourceValue != null; } // Or anything, just try to get the value. 
    catch { return false; } 
})); 
0

我相信Automapper提供這樣的:

private static void CreateMappings(IMapperConfiguration config) 
{ 
    config.CreateMap<SrcRow, DestDto>() 
    .ForAllMembers(opt => opt.ResolveUsing(
    ... 
); // or use opt.Condition() 
}