21
\$\begingroup\$

I'm using Automapper to do some mapping from XSD-generated serialization object to more sane POCO's.

I'm having an issue with a particular type of mapping.

public class SourceOuterObject
{
 public SourceSet SourceSet { get; set; }
}
public class SourceSet
{
 public List<SourceObject> SourceList{ get; set; }
}

I want to map this to:

public class TargetOuterObject
{
 public List<TargetObject> TargetList{ get; set; }
}

I have tried a wide variety of mapping configurations, but the only thing that I've been able to make work is this:

Mapper.CreateMap<SourceOuterObject, TargetOuterObject>();
Mapper.CreateMap<SourceObject, TargetObject>();
Mapper.CreateMap<SourceSet, List<TargetObject>>()
 .ConvertUsing(ss => ss.SourceList.Select(bs => Mapper.Map<SourceObject, TargetObject>(bs)).ToList());

This works but seems to be way more complicated than it should be - I feel dirty calling a mapping within a mapping config.

Is this the best I can hope for or is there a better way?

asked Nov 25, 2014 at 21:10
\$\endgroup\$
1
  • 1
    \$\begingroup\$ You could create a topic on stackoverflow, i think they can help you better. \$\endgroup\$ Commented Dec 1, 2014 at 16:01

1 Answer 1

22
\$\begingroup\$

When dealing with collections, the trick is always to set up a mapping of the items in the collections and never (well, I've never seen a case that needed) a mapping from one collection to another. That's the point of the generic.

The trick I always use is to work backwards, starting with a mapping between the types inside the collections and then going up a level. If one object needs to go up 2 levels, it's time to use ForMember to get to a nested property.

What you want to do in this case is to set up the following mappings:

Mapper.CreateMap<SourceObject, TargetObject>();
Mapper.CreateMap<SourceOuterObject, TargetOuterObject>()
 .ForMember(dest => dest.TargetList, opt => opt.MapFrom(src => src.SourceSet.SourceList);
answered Jan 30, 2015 at 18:41
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.