Home > Net >  Mapping nested list using Automapper
Mapping nested list using Automapper

Time:11-23

I have 3 classes Person, Hobby and Customer

public class Person {
    public string Name {get;set;}
    public List<Hobby> Hobbies {get;set;}
}

public class Hobby {
    public string Type {get;set;}
}

public class Customer {
    public string CustomerName {get;set;}
    public string TypeOfHobby {get;set;}
}

With the following Automapper mapping

CreateMap<Customer, Person>()
    .ForMember(dest => dest.Name, opt => opt.MapFrom(scr => src.CustomerName))

CreateMap<Customer, Hobby>()
    .ForMember(dest => dest.Type, opt => opt.MapFrom(scr => src.TypeOfHobby))

I now create a list of Persons and Customers

var persons = new List<Person>()
var customers = new List<Customers>(){
    new(){
        CustomerName = "john doe",
        TypeOfHobby = "reading"
    },
    new(){
        CustomerName = "jane doe",
        TypeOfHobby = "sports"
    }
}

I want to be able to map from the customers list to the persons list as follows:

[
    {
        "name": "john doe",
        "hobbies": [
            {
                "type": "reading"
            }
        ]
    },
    {
        "name": "jane doe",
        "hobbies": [
            {
                "type": "sports"
            }
        ]
    }
]

I have tried the following:

var mappedPersons = _mapper.Map<List<Person>>(customers)

but I'm not sure how to do the mapping for the Hobbies inside each mappedPersons

CodePudding user response:

I think, in your case, just constructing a new list will do the job,

CreateMap<Customer, Person>()
     .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.CustomerName))
     .ForMember(dest => dest.Hobbies, opt => opt.MapFrom(src => new List<Hobby>
     {
         new Hobby
        {
            Type = src.TypeOfHobby
        }
     }));

CodePudding user response:

For your scenario, you need a Custom Value Resolver for mapping the Hobbies property in the destination class.

CreateMap<Customer, Person>()
    .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.CustomerName))
    .ForMember(dest => dest.Hobbies, opt => opt.MapFrom((src, dest, destMember, ctx) =>
    {
        List<Hobby> hobbies = new List<Hobby>();
        hobbies.Add(ctx.Mapper.Map<Hobby>(src));
        return hobbies;
    }));

Demo @ .NET Fiddle

  • Related