1

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));
1
  • 1
    No directly linked to the condition but you don't need to mention the MapFrom portion since both the source and destination collections have the same name. .ForMember(des => des.Divisions, e => e.Condition(source => !source.Divisions.IsNullOrEmpty())) Commented Aug 28, 2013 at 19:58

1 Answer 1

1

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.