DEV Community

Cover image for How to map Nested Object mappings with AutoMapper C#
Matheus Paixão
Matheus Paixão

Posted on

How to map Nested Object mappings with AutoMapper C#

So let me start by saying that I decided to share this content because I just couldn't find the perfect answer on internet, it took me half a day to figure this out.

Gif

As a good practice, we are using the RequestDTO and a ResponseDTO, so we don't return the same model we receive.

RequestDTO

    public class Attributes
    {
        public string type { get; set; }
        public string url { get; set; }
    }

    public class Keep
    {
        public Attributes attributes { get; set; }
        public DateTime LastModifiedDate { get; set; }
        public string Email { get; set; }            
    }

    public class Discart
    {
        public Attributes attributes { get; set; }
        public DateTime LastModifiedDate { get; set; }
        public string Email { get; set; }

    }

    public class Root
    {            
        public List<DataWeNeed> Keep { get; set; }
        public List<DataWeDontNeed> Discart { get; set; }
        public string userId { get; set; }
    }
}
Enter fullscreen mode Exit fullscreen mode

ResponseDTO

    public class Attributes
    {
        public string type { get; set; }
        public string url { get; set; }
    }

    public class ResponseKeep
    {
        public Attributes attributes { get; set; }
        public DateTime LastModifiedDate { get; set; }
        public string Email { get; set; }            
    }
Enter fullscreen mode Exit fullscreen mode

AutoMapper Basic Configuration Startup.cs



 public void ConfigureServices(IServiceCollection services)
        {            
            services.AddAutoMapper(typeof(Startup));
        }


Enter fullscreen mode Exit fullscreen mode

Controller



public class Controller : ControllerBase
    {
//AutoMapper Dependency Injection
        private readonly IMapper _map;

        public ValuesController(IMapper map)
        {
            _map = map;
        }

        [HttpPost]
        [Route("api")]
        public Keep Post(Object value)
        {            
//Deserialize de Json request into our Object
            Root deserialized = JsonConvert.DeserializeObject<Root>(value.ToString());

//Mapping the first item of the Keep List into the responseDto
            var responseDTO = _map.Map<ResponseDTO>(deserealized.Keep.FirstOrDefault());

            return responseDTO;
        }
    }


Enter fullscreen mode Exit fullscreen mode

Mapping Profile

Here is where the magic happens.

To make sure the the automapper does the right mapping and doesn't returns an exception we must resolve the mapping in details.
How?

As we have different Objects, we need to tell automapper which objects and fields are mapped and from where, using the method ForMember and MapFrom.

See that the main Object the automapper does automatically without mapping the fields, but, when it comes to the Object Value Attributes I had to map one by one so it would understand where the information is sourced and where the information the designated.



public AutoMapper()
        {
            CreateMap<RequestDTO.Attributes, ResponseDTO.Attributes>()
                .ForMember(
                    dest => dest.type,
                    opt => opt.MapFrom(src => src.type)
                )
                .ForMember(
                    dest => dest.url,
                    opt => opt.MapFrom(src => src.url)
                );
            CreateMap<Keep, ResponseKeep>()
                .ForMember(
                dest => dest.attributes,
                opt => opt.MapFrom(src => src.attributes));
        }


Enter fullscreen mode Exit fullscreen mode

That's the solution I found to solve my issue, If you have another solution, specially that doesn't involve mapping field by field.

Obrigado

Top comments (0)