patterncsharpMajor
Automapper - Mapping a nested collection to a list
Viewed 0 times
collectionautomappernestedmappinglist
Problem
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.
I want to map this to:
I have tried a wide variety of mapping configurations, but the only thing that I've been able to make work is this:
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?
I'm having an issue with a particular type of mapping.
public class SourceOuterObject
{
public SourceSet SourceSet { get; set; }
}
public class SourceSet
{
public List SourceList{ get; set; }
}I want to map this to:
public class TargetOuterObject
{
public List 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();
Mapper.CreateMap();
Mapper.CreateMap>()
.ConvertUsing(ss => ss.SourceList.Select(bs => Mapper.Map(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?
Solution
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:
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();
Mapper.CreateMap()
.ForMember(dest => dest.TargetList, opt => opt.MapFrom(src => src.SourceSet.SourceList);Code Snippets
Mapper.CreateMap<SourceObject, TargetObject>();
Mapper.CreateMap<SourceOuterObject, TargetOuterObject>()
.ForMember(dest => dest.TargetList, opt => opt.MapFrom(src => src.SourceSet.SourceList);Context
StackExchange Code Review Q#70856, answer score: 22
Revisions (0)
No revisions yet.