如何在列表为空但不为空时忽略列表映射?

时间:2013-08-28 10:39:20

标签: c# .net automapper conditional-statements

当列表为空但不为空时,如何忽略列表映射。

如果source.Divisions(IEnumerable)为null或为空,则不应映射des.Divisions:

 Mapper.CreateMap<Model.Event, DataContracts.Event>()
   .ForMember(des => des.Divisions, e => e.MapFrom(source => source.Divisions))

我找到了以下解决方案:

  Mapper.CreateMap<Model.Event, DataContracts.Event>()
       .ForMember(des => des.Divisions, e => { 
e.Condition(source => !source.Divisions.IsNullOrEmpty()));
e.MapFrom(source => source.Divisions));
});

有没有进一步简化上述内容?

例如通过创建扩展方法。

Mapper.CreateMap<Model.Event, DataContracts.Event>()
           .ForMember(des => des.Divisions, e => e.MapListIfNotEmpty(source => source.Divisions));

1 个答案:

答案 0 :(得分:0)

我写了这个扩展名,希望它有所帮助!

 public static void MapListIfNotEmpty<TSource, TMapFrom>(this IMemberConfigurationExpression<TSource> map,
        Func<TSource, IEnumerable<TMapFrom>> mapFrom)
    {
        map.Condition(src => !mapFrom(src).IsNullOrEmpty());

        map.MapFrom(mapFrom);
    }

你可以像这样使用它:

 Mapper.CreateMap<Model.Event, DataContracts.Event>()
                .ForMember(des => des.Divisions, e => e.MapListIfNotEmpty(source => source.Geographies));