简体   繁体   中英

Map 2 lists into a list of DTOs using AutoMapper

I have two tables (lists): customers and sales that have an one-to-many relationship. I'm trying to create an automap that results in a list populated with CustomerSalesDto. For every Sale object a new CustomerSalesDto should be created with the Sale information and some of the information from the Customer who made the sale.

Can this be done with Automapping and how would I accomplish this?

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
}

You can do something like this:

First create a map from Tuple<Sale, Customer> to CustomerSalesDto like this:

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));

Then you can create a method to match each sale with the corresponding customer and then use AutoMapper to create a list of CustomerSalesDto objects like this:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM