【问题标题】:Map 2 lists into a list of DTOs using AutoMapper使用 AutoMapper 将 2 个列表映射到 DTO 列表
【发布时间】:2015-09-28 23:38:33
【问题描述】:

我有两个表(列表):customers 和 sales,它们具有一对多的关系。我正在尝试创建一个自动映射,该自动映射会生成一个填充有 CustomerSalesDto 的列表。对于每个销售对象,都应使用销售信息和进行销售的客户的一些信息创建一个新的 CustomerSalesDto。

这可以通过 Automapping 完成吗?我该如何完成?

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
}

【问题讨论】:

  • 如果Sale 有一个Customer 类型的属性已完全填充,那么是的,这是可能的。
  • 如果类型保持为 int 有什么解决方法吗?我正在使用一个框架,当他进行销售(而不是对象)时,它会自动将客户 ID 注入数据库。
  • 您使用实体框架还是手动执行此操作?你如何填充Sale 对象?
  • 使用服务和存储库模式(内部的实体框架)填充销售。在与“CreateSale()”函数相同的服务中应该有另一个函数“GetSales()”,其中所有销售都与匹配的用户信息一起存储在 DTO 列表中。
  • TBH a Sale 有一个关联的Customer,因此您可以通过向Sale 添加一个附加属性来对此进行建模 - 否则要创建您的CustomerSalesDto,您需要访问存储库以获取销售和客户数据 - 但是您如何从 CustomerSalesDto 知道客户是谁以及销售是什么? (类中没有id)

标签: c# asp.net-mvc asp.net-mvc-5 automapper automapping


【解决方案1】:

你可以这样做:

首先创建一个从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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-09
    • 2011-08-01
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 2012-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多