0

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

2 Answers 2

1

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
        }
     }));
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.