Search code examples
c#automapper

How to map nested object with AutoMapper?


Let's say we have this Entity and the corresponding Dto:

public class MyEntity
{
    public string Name {get; set;}
}

public class MyEntityDto
{
    public string Name {get;set;}
}

And this Aggregate and corresponding Dto:

public class MyAgg
{
    public string SomeProp {get;set;}
    public MyEntity Entity {get;set;}
}

public class MyAggDto
{
    public string SomeProp {get;set;}
    public AggDataDto Data {get;set;}
    
    public class AggDataDto
    {
        public MyEntityDto Entity {get;set;}
    }
}

Here is the mapping profile:

public class MyProfile : Profile
{
    public MyProfile()
    {
        CreateMap<MyEntity, MyEntityDto>();
        CreateMap<MyAgg, MyAggDto>()
            .ForMember(dest => dest.Data, opt => opt.MapFrom(src => {
                return new MyAggDto.AggDataDto
                {
                    /*
                        Can I inject and use IMapper here to get MyEntityDto from src.Entity ?
                        Should I create the Dto with new MyEntityDto(...) ?
                        Any other approach ?
                    */
                    Entity = ...
                }
            }));
    }
}

How can I Map nested object?


Solution

    1. You should create a mapping rule from MyEntity to MyAggDto.AggDataDto.

    2. For the mapping rule from MyAgg to MyAggDto, map the source's Entity member to the destination's Data member.

    public class MyProfile : Profile
    {
        public MyProfile()
        {
            CreateMap<MyEntity, MyEntityDto>();
            
            CreateMap<MyEntity, MyAggDto.AggDataDto>()
                .ForMember(dest => dest.Entity, opt => opt.MapFrom(src => src));
            
            CreateMap<MyAgg, MyAggDto>()
                .ForMember(dest => dest.Data, opt => opt.MapFrom(src => src.Entity));
        }
    }