1

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

如果 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));
4

1 回答 1

1

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

 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));
于 2013-08-29T09:49:04.783 回答