Search code examples
c#automapper

Nested mapping with Automapper


I have the following classes:

 public class Product
 {
     public int Id { get; set; }
     public string Name { get; set; }
     public string Description { get; set; }
     public ProductStatus Status { get; set; }
     public List<ProductPrice> Prices { get; set; }
     public List<ProductStock> Stocks { get; set; }
 }

public class ProductPrice
{
    public int Id { get; set; }
    public int ProductId { get; set; }        
    public decimal Price { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}

 public class ProductWithPricesResponse
 {
    public string Name { get; set; }
    public string Description { get; set; }
    public List<ProductPriceResponse> Prices { get; set; }
 }

public class ProductPriceResponse
{
    public decimal Price { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}

I want to map from Product to ProductWithPricesResponse using Automapper, but I don't know how to make the nested mapping between the list of ProductPrices from Product to the list of ProductPriceResponsepero from ProductWithPricesResponse.

I tried this in my ProductProfile:

public ProductProfile(IMapper mapper)
{
    _mapper = mapper;
    CreateMap<Product, ProductWithPricesResponse>()
        .ConvertUsing(x => x.Prices.Select(y => _mapper.Map<ProductPrice, ProductPriceResponse>(y)).ToList());
}

What I wanted to do there was, first telling Automapper that I'm gonna map from Product to ProductWithPricessResponse, and inside the list of Prices of Product, convert each item of ProductPrice to an item of ProductPriceResponse, but I get an error telling me that I cannot implicity convert from a generic list of ProductPriceResponse to an object of ProductWithPricesresponse.

Someone already did this type of nested mapping and can help me?


Solution

  • You need to configure a mapping for each class you want to map:

    CreateMap<Product, ProductWithPricesResponse>() /* ... */
    CreateMap<ProductPrice, ProductPriceResponse>() /* ... */ 
    

    then it should work out-of-the-box.