Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to merge two nested object into one using AutoMapper

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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); 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading