使用AutoMapper

时间:2015-09-28 14:06:37

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

我有两个表(列表):具有一对多关系的客户和销售。我正在尝试创建一个自动生成器,该生成器会生成一个填充了CustomerSalesDto的列表。对于每个Sale对象,应使用销售信息和来自进行销售的客户的一些信息创建新的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
}

1 个答案:

答案 0 :(得分:0)

您可以这样做:

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