Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use mapper.Map inside MapperConfiguration of AutoMapper?

I need to map an object to another one using AutoMapper. The tricky question is how can I access an instance of the mapper (instance of IMapper) inside of the mapping configuration or inside of a custom type converter?

The code below does not work, however it is an example of what I would like to achieve - please notice the mapper.Map calls and assume that mappings Customer => CustomerDto and Customer => DetailedCustomerDto are defined.

var config = new MapperConfiguration(     cfg => cfg.CreateMap<Order, OrderDto>()         .ForMember(dst => dst.Customer, src => src.ResolveUsing(o => {             return o.Type == 1                 ? mapper.Map<Customer, CustomerDto>(o.Customer)                 : mapper.Map<Customer, DetailedCustomerDto>(o.Customer)             })     ); 

The client part is:

var mapper = config.CreateMapper(); var orderDto = mapper.Map<Order, OrderDto>(order); 

The simplified version of objects I want to map is:

public class Order {     public int Type { get; set; }     public Customer Customer { get; set; } }  public class Customer {     public long Id { get; set; }     public string Name { get; set; } }  public class OrderDto {     public CustomerDto Customer { get; set; } }  public class CustomerDto {     public long Id { get; set; } }  public class DetailedCustomerDto : CustomerDto {     public string Name { get; set; } } 

As you see from the codes above, based on the value of Order.Type, the mapper should map the property Order.Customer to different targets. As one target (DetailedCustomerDto) inherits from the other one (CustomerDto) it becomes a bit tricky.

Please notice that usage of the obsolete and deprecated static method Mapper.Map is NOT an option.

like image 683
Anton Avatar asked May 06 '16 12:05

Anton


People also ask

Does AutoMapper map nested objects?

With both flattening and nested mappings, we can create a variety of destination shapes to suit whatever our needs may be.

How do I use AutoMapper to list a map?

How do I use AutoMapper? First, you need both a source and destination type to work with. The destination type's design can be influenced by the layer in which it lives, but AutoMapper works best as long as the names of the members match up to the source type's members.

Can AutoMapper map enums?

The built-in enum mapper is not configurable, it can only be replaced. Alternatively, AutoMapper supports convention based mapping of enum values in a separate package AutoMapper.


2 Answers

As of AutoMapper 8.0 and up The answer below for 5.1.1 still applies, but note that the use of ResolveUsing has been replaced with an overload of MapFrom, but the signature has otherwise remained consistent.

As of AutoMapper 5.1.1

You can get to the mapper using another overload of ResolveUsing with four parameters, fourth of which is ResolutionContext (context.Mapper):

var config = new MapperConfiguration(     cfg => {         cfg.CreateMap<Customer, CustomerDto>();         cfg.CreateMap<Customer, DetailedCustomerDto>();         cfg.CreateMap<Order, OrderDto>()              .ForMember(dst => dst.Customer, src => src.ResolveUsing((order, orderDto, i, context) => {                 return order.Type == 1                 ? context.Mapper.Map<Customer, CustomerDto>(order.Customer)                 : context.Mapper.Map<Customer, DetailedCustomerDto>(order.Customer);         }));  });   var orderTypeOne = new Order();  orderTypeOne.Type = 1;  orderTypeOne.Customer = new Customer() {     Id = 1  };   var dto = config.CreateMapper().Map<Order, OrderDto>(orderTypeOne);  Debug.Assert(dto.Customer.GetType() == typeof (CustomerDto));   var orderTypeTwo = new Order();  orderTypeTwo.Type = 2;  orderTypeTwo.Customer = new Customer() {      Id = 1  };  dto = config.CreateMapper().Map<Order, OrderDto>(orderTypeTwo);  Debug.Assert(dto.Customer.GetType() == typeof (DetailedCustomerDto)); 

Prior to AutoMapper 5.1.1

You can get to the mapper using another overload of ResolveUsing with two parameters, first of which is ResolutionResult (result.Context.Engine.Mapper):

var config = new MapperConfiguration(     cfg => {         cfg.CreateMap<Customer, CustomerDto>();         cfg.CreateMap<Customer, DetailedCustomerDto>();         cfg.CreateMap<Order, OrderDto>()              .ForMember(dst => dst.Customer, src => src.ResolveUsing((result, order) => {                 return order.Type == 1                 ? result.Context.Engine.Mapper.Map<Customer, CustomerDto>(order.Customer)                 : result.Context.Engine.Mapper.Map<Customer, DetailedCustomerDto>(order.Customer);         }));  });   var orderTypeOne = new Order();  orderTypeOne.Type = 1;  orderTypeOne.Customer = new Customer() {     Id = 1  };   var dto = config.CreateMapper().Map<Order, OrderDto>(orderTypeOne);  Debug.Assert(dto.Customer.GetType() == typeof (CustomerDto));   var orderTypeTwo = new Order();  orderTypeTwo.Type = 2;  orderTypeTwo.Customer = new Customer() {      Id = 1  };  dto = config.CreateMapper().Map<Order, OrderDto>(orderTypeTwo);  Debug.Assert(dto.Customer.GetType() == typeof (DetailedCustomerDto)); 
like image 134
Evk Avatar answered Sep 29 '22 01:09

Evk


In addition to Evk's great answer, which helped me, if you need to do a mapping inside a mapping inside a config/profile that requires a custom constructor (i.e. the type has no default constructor), the following will work in v5.2.0:

CreateMap<Models.Job, Models.API.Job>(MemberList.Source);  CreateMap<StaticPagedList<Models.Job>, StaticPagedList<Models.API.Job>>()                 .ConstructUsing((source, context) => new StaticPagedList<Models.API.Job>(                     context.Mapper.Map<List<Models.Job>, List<Models.API.Job>>(source.ToList()),                     source.PageNumber,                     source.PageSize,                     source.TotalItemCount)); 

In this example I'm mapping the X.PagedList custom collection type of one object type onto an equivalent collection of another object type. The first parameter to the lamdba expression is your source object, the second is your ResolutionContext from which you can access a mapper instance to map from.

like image 43
Breeno Avatar answered Sep 28 '22 23:09

Breeno