2012-11-02 168 views
12

我正在使用automapper,我想知道是否有可能忽略字段的映射,當這是null。Automapper - 忽略條件映射

這是我的代碼:

.ForMember(dest => dest.BusinessGroup_Id, 
      opt => opt.MapFrom(src => (int)src.BusinessGroup)) 
  • src.BusinessGroup type = "enum"
  • dest.BusinessGroup_Id = int

它以則會忽略,如果src.BusinessGroup = NULL是映射的目標。

回答

25

我認爲NullSubstitute選項就可以了

.ForMember(d => d.BusinessGroup_Id, o => o.MapFrom(s => (int?)s.BusinessGroup)); 
.ForMember(d => d.BusinessGroup_Id, o => o.NullSubstitute(0)); 

順便說一句,你可以寫在映射行動的條件:

.ForMember(d => d.BusinessGroup_Id, 
      o => o.MapFrom(s => s.BusinessGroup == null ? 0 : (int)s.BusinessGroup)); 

UPDATE如果不能分配一些默認值,以你的財產,你可以忽略它,並且只映射不是空的:

.ForMember(d => d.BusinessGroup_Id, o => o.Ignore()) 
.AfterMap((s, d) => 
    { 
     if (s.BusinessGroup != null) 
      d.BusinessGroup_Id = (int)s.BusinessGroup; 
    }); 
+0

嗨lazyberezovsky,感謝您的快速響應!我不能將0設置爲BusinessGroup_Id,因爲這是DB – user1520494

+2

Ty上的一個前兆!您的最新更新對我來說非常適合! :) – user1520494