2015-10-19 49 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); 
}