Hi I have been using AutoMapper to convert my objects, and now I’m trying to merge two nested objects into one, but I can’t figure out how to do it.
I have the following code:
These are my source objects
class SourceSubItemA
{
string subPropertyA;
}
class SourceSubItemB
{
string subPropertyB;
}
class Source
{
SourceSubItemA subItemA;
SourceSubItemB subItemB;
}
Destination objects
class DestinationSubItem
{
string propertyA;
string propertyB;
}
class Destination
{
DestinationSubItem destItem;
}
This is my Automapper configuration
Mapper.CreateMap<SourceSubItemA, DestinationSubItem>()
.ForMember(dest => propertyA, opt => opt.MapFrom(src => src.subPropertyA));
Mapper.CreateMap<SourceSubItemB, DestinationSubItem>()
.ForMember(dest => propertyB, opt => opt.MapFrom(src => src.subPropertyB));
// Probably I have to do something more here.
Mapper.CreateMap<Source, Destination>()
.ForMember(dest => dest.destItem, opt => opt.MapFrom(src => src.subItemA));
And finally I’m using the mapper by this way
Mapper.Map<Destination>(sourceObject);
The expected result must be a Destination object with a subitem with both properties filled.
Please Help!
>Solution :
As I can see, Destination is just a wrapper of DestinationSubItem that is the one that really needs to get the values from Source.
In that case, you could define a mapper from Source to Destination that puts in dest.destItem the result of mapping from Source directly to DestinationSubItem.
Here an example:
Mapper.CreateMap<Source, Destination>()
.ForMember(dest => dest.destItem, opt => opt.MapFrom(src => Mapper.Map<DestinationSubItem>(src));
Mapper.CreateMap<Source, DestinationSubItem>()
.ForMember(dest => dest.propertyA, opt => opt.MapFrom(src => src.subItemA.subPropertyA)
.ForMember(dest => dest.propertyB, opt => opt.MapFrom(src => src.subItemB.subPropertyB);