Reputation: 27011
How to ignore a list mapping when the list is empty but not null.
if source.Divisions (which is an IEnumerable) is null or empty then the des.Divisions shouldn't be mapped:
Mapper.CreateMap<Model.Event, DataContracts.Event>()
.ForMember(des => des.Divisions, e => e.MapFrom(source => source.Divisions))
I've found the below solution:
Mapper.CreateMap<Model.Event, DataContracts.Event>()
.ForMember(des => des.Divisions, e => {
e.Condition(source => !source.Divisions.IsNullOrEmpty()));
e.MapFrom(source => source.Divisions));
});
Is there anyway to simplify the above further?
e.g by creating an extension method.
Mapper.CreateMap<Model.Event, DataContracts.Event>()
.ForMember(des => des.Divisions, e => e.MapListIfNotEmpty(source => source.Divisions));
Upvotes: 1
Views: 1241
Reputation: 27011
I wrote this extension, hope it helps!
public static void MapListIfNotEmpty<TSource, TMapFrom>(this IMemberConfigurationExpression<TSource> map,
Func<TSource, IEnumerable<TMapFrom>> mapFrom)
{
map.Condition(src => !mapFrom(src).IsNullOrEmpty());
map.MapFrom(mapFrom);
}
and you can use it like this:
Mapper.CreateMap<Model.Event, DataContracts.Event>()
.ForMember(des => des.Divisions, e => e.MapListIfNotEmpty(source => source.Geographies));
Upvotes: 1