简体   繁体   中英

Map List<> with Automapper?

I have two classes:

public class CustomerDTO
{

public string Name {get;set;}
public List<Order> Orders {get;set;}

}

public class OrderDTO
{
public string Name {get;set;}
public string Description {get;set;}
public decimal Cost{get;set;}
}

I am using AutoMapper for .NET 3.5 and currently doing the following in my Application_StartUp:

Mapper.CreateMap<Customer, CustomerDTO>();
Mapper.CreateMap<Order,OrderDTO>();

This is a simplified example as I named my DTO properties different than my entity properties, so I used ForMember, but I am unclear on how to map Orders to Customer:

I tried:

Mapper.CreateMap<Customer, CustomerDTO()
.ForMember(dest => dest.Orders, opt=> opt.MapFrom(src=>src.Orders));

but it does not find src.Orders .

If I do indeed need to have both CreateMap statements, does AutoMapper "automatically" link the objects Customer to Orders ?

Yes, you need to tell AutoMapper about each mapping. It will not guess for you. So, if an OrderDTO should map to an Order , you must tell AutoMapper that. You must also specify the reverse relationship if that's needed as well (ie Order should map to OrderDTO ).

In other words, for bi-directional mapping you would need:

Mapper.CreateMap<Order, OrderDTO>();
Mapper.CreateMap<OrderDTO, Order>();

As far as Customer goes, if both Customer and CustomerDTO have a property named Orders , you don't need to do anything else. As long as you've told AutoMapper to map between Order and OrderDTO and Customer and CustomerDTO , it will automatically map your Order when you map Customer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM