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