当列表为空但不为空时如何忽略列表映射。
如果 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));