Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper convert from multiple sources

Tags:

c#

automapper

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) ; 

I cannot seem to find any example for this scenario. Is this possible ?

Note: Example is not-real, just for this question.

like image 487
Bart Calixto Avatar asked Jan 28 '14 18:01

Bart Calixto


People also ask

Why you should not use AutoMapper?

1. If you use the convention-based mapping and a property is later renamed that becomes a runtime error and a common source of annoying bugs. 2. If you don't use convention-based mapping (ie you explicitly map each property) then you are just using automapper to do your projection, which is unnecessary complexity.

Does AutoMapper map both ways?

Yes, or you can call CreateMap<ModelClass, ViewModelClass>(). ReverseMap() .

Is AutoMapper bidirectional?

What is AutoMapper Reverse Mapping in C#? The Automapper Reverse Mapping is nothing but the two-way mapping which is also called as bidirectional mapping.


1 Answers

You cannot directly map many sources to single destination - you should apply maps one by one, as described in Andrew Whitaker answer. So, you have to define all mappings:

Mapper.CreateMap<People, PeoplePhoneDto>(); Mapper.CreateMap<Phone, PeoplePhoneDto>()         .ForMember(d => d.PhoneNumber, a => a.MapFrom(s => s.Number)); 

Then create destination object by any of these mappings, and apply other mappings to created object. And this step can be simplified with very simple extension method:

public static TDestination Map<TSource, TDestination>(     this TDestination destination, TSource source) {     return Mapper.Map(source, destination); } 

Usage is very simple:

var dto = Mapper.Map<PeoplePhoneDto>(people)                 .Map(phone); 
like image 149
Sergey Berezovskiy Avatar answered Sep 22 '22 11:09

Sergey Berezovskiy