AutoMapper convert from multiple sources

automapper, c#

Solution

Try this if you're using C# 7+ (a slight variation of @Paweł Bejgerthat's answer that will make it even simpler):

Mapper.CreateMap<(People people, Phone phone), PeoplePhoneDto>()
    .ForMember(d => d.FirstName, opt => opt.MapFrom(s => s.people.FirstName))
    .ForMember(d => d.LastName, opt => opt.MapFrom(s => s.people.LastName))
    .ForMember(d => d.Number, opt => opt.MapFrom(s => s.phone.Number ));

And then use it like this:

var peoplePhoneDto = EntityMapper.Map<PeoplePhoneDto>((people, phone));

And yes, you will need a couple of brackets around the arguments, it's not a mistake. The reason behind it is that you're passing one single source (not two) which happens to be a (People, Phone) tuple.

Problem

Let's say I have two model classes: ``` public class People { public string FirstName {get;set;} public string LastName {get;set;} } ``` Also have a class Phone: ``` public class Phone { public string Number {get;set;} } ``` And I want to convert to a PeoplePhoneDto like this: ``` public class PeoplePhoneDto { public string FirstName {get;set;} public string LastName {get;set;} public string PhoneNumber {get;set;} } ``` Let's say in my controller I have: ``` var people = repository.GetPeople(1); var phone = repository.GetPhone(4); // normally, without automapper I would made return new PeoplePhoneDto(people, phone) ; ``` Is this possible ?

Original source

Related problems