2015-10-19 50 views
0

使用automap映射多對多關係。Automapper創建具有多對多關係的新行

考慮下面的例子

public class Customer 
{ 
    public string FirstName{get;set;} 
    public string LastName{get;set;} 
    public int age{get;set;} 
    public List<Details> Details {get;set;} 
} 

public class Details 
{ 
    public int ID{get;set;} 
    public string Designation{get;set;} 
} 

我要自動映射上述實體到新的DTO對象像

public class CustomerDto 
{ 
    public string FirstName{get;set;} 
    public string LastName{get;set;} 
    public int age{get;set;} 
    public int ID{get;set;} 
    public string Designation{get;set;} 
} 

所以在客戶的詳細信息列表中的所有條目應該被視爲新行給顧客的DTO。這個怎麼做 ?

+0

所以,如果你有1'Customer'對象有10'Details',您希望獲得10個'CustomerDto'對象? –

回答

1

因此,您有一個Customer對象,並且您想將其映射到。此列表將包含Customer對象中每個細節的單個項目。

下面是做到這一點的一種方法:

首先,創建兩個映射,從一個Customer映射CustomerDto,另外一個從DetailsCustomerDto

AutoMapper.Mapper.CreateMap<Customer, CustomerDto>(); 
AutoMapper.Mapper.CreateMap<Details, CustomerDto>(); 

現在,讓我們假設你有變量customer一個Customer對象,你可以做到以下幾點:

List<CustomerDto> dtos = AutoMapper.Mapper.Map<List<CustomerDto>>(customer.Details); 

foreach (var dto in dtos) 
{ 
    AutoMapper.Mapper.Map(customer, dto); 
}