2017-02-01 166 views
0

似乎有很多關於如何在最新更新AutoMapper中實現這一點的困惑。我使用的是AutoMapper 5.2.0,而在Github Issues和SO上找到的舊解決方案無法使用。AutoMapper忽略NULL值

我的要求是忽略映射如果源值爲空值或空白(字符串)或0(對於int)

回答

1

嘗試使用此擴展用於檢查是否爲空:

public static void MapFromIfNotNull<TSource, TDestination, TProperty>(
     this IMemberConfigurationExpression<TSource, TDestination, TProperty> map, 
     Expression<Func<TSource, object>> selector) 
     { 
      var function = selector.Compile(); 
      map.Condition(source => function(source) != null); 
      map.MapFrom(selector); 
     } 

然後使用

CreateMap<EmployeeDTO, Employee>() 
    .ForMember(dest => dest.MOBILE, opts => opts.MapFromIfNotNull(src => src.MobilePhone))