Ajay Srikanth
Ajay Srikanth

Reputation: 1185

C# Automapper on the nested list

I've the following dtos and I'm trying to use automapper, but couldn't quite understand on how to do the same, as this is the first time I'm using automapper any help is really appreciated

string order {get;set;}
string orderType {get;set;}
List<OrderItem> Items {get;set;}
}

public class OrderItem{
string itemID {get;set;}
Price price {get;set;}
}

public class Price {
string total {get;set;}
string regular {get;set;}
}

public class request {
string order {get;set;}
string orderType {get;set;}
List<Item> Items {get;set;}
}

public class Item {
string itemID {get;set;}
string itemPrice {get;set;}
string regularPrice {get;set;}
}


I'm trying the following

var config = new MapperConfiguration(cfg => {
cfg.CreateMap<request,requestDTO>()
.ForMember(dest => dest.order, act=>act.MapFrom(src => src.order))
.ForMember(dest => dest.orderType, act=>act.MapFrom(src => src.orderType))
})

How do I create mapping to map 

**
src.item.itemID to dest.item.itemID
src.item.itemPrice to dest.item.price.total
src.item.regularPrice to dest.item.price.regular**

for all the items in my source array

Upvotes: 0

Views: 839

Answers (1)

Oignon_Rouge
Oignon_Rouge

Reputation: 305

Just create another map for Item and OrderItem as follows:

cfg.CreateMap<Item, OrderItem>()
.ForPath(dest => dest.price.total, act => act.MapFrom(src => src.itemPrice))
.ForPath(dest => dest.price.regular, act =>act.MapFrom(src => src.item.regularPrice));

Also note that the mapper <request,requestDTO> does not need any explicit ForMember call, as both objects have identical property names:

cfg.CreateMap<request,requestDTO>();

Upvotes: 1

Related Questions