使用AutoMapper将2个列表映射为dto列表
本文关键字:列表 映射 dto 2个 AutoMapper 使用 | 更新日期: 2023-09-27 18:14:47
我有两个表(列表):客户和销售,它们具有一对多关系。我正在尝试创建一个自动映射,其结果是一个由CustomerSalesDto填充的列表。对于每个Sale对象,应该创建一个新的CustomerSalesDto,其中包含Sale信息和来自进行销售的Customer的一些信息。
这可以通过自动映射完成吗?我该如何完成?
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
public class Sale
{
public int Id { get; set; }
public double Price { get; set; }
public DateTime Date { get; set; }
public int CustomarId { get; set;} // Id from Customer who made a sale.
}
public class CustomerSalesDto
{
public double Price { get; set; } // from Sale
public DateTime Date { get; set; } // from Sale
public string Name { get; set; } // from Customer
public string Email { get; set; } // from Customer
}
你可以这样做:
首先像这样创建一个从Tuple<Sale, Customer>
到CustomerSalesDto
的映射:
AutoMapper.Mapper.CreateMap<Tuple<Sale, Customer>, CustomerSalesDto>()
.ForMember(t => t.Name, m => m.MapFrom(f => f.Item2.Name))
.ForMember(t => t.Email, m => m.MapFrom(f => f.Item2.Email))
.ForMember(t => t.Date, m => m.MapFrom(f => f.Item1.Date))
.ForMember(t => t.Price, m => m.MapFrom(f => f.Item1.Price));
然后您可以创建一个方法来匹配每个销售与相应的客户,然后使用AutoMapper创建一个CustomerSalesDto
对象列表,如下所示:
public List<CustomerSalesDto> Convert(List<Sale> sales, List<Customer> customers)
{
List<CustomerSalesDto> result = new List<CustomerSalesDto>();
Dictionary<int, Customer> customer_dictionary = customers.ToDictionary(x => x.Id); //This is done to speed things up
foreach (Sale sale in sales)
{
if(!customer_dictionary.ContainsKey(sale.CustomarId))
throw new Exception("Could not find the customer");
Customer customer = customer_dictionary[sale.CustomarId];
result.Add(AutoMapper.Mapper.Map<CustomerSalesDto>(new Tuple<Sale, Customer>(sale , customer)));
}
return result;
}