Isaac Levin Isaac Levin - 4 days ago 5
C# Question

AutoMapper Map and Flatten Entity with List

I have the following data model

public class Products
{
public string Name { get; set; }
public ICollection<ProductSize> ProductSizes { get; set; }
}

public class ProductSize
{
public double UnitSize { get; set; }
public ICollection<ProductPackage> ProductPackages { get; set; }
}

public class ProductPackage
{
public int ItemsPerPack { get; set; }
public ICollection<ProductPrice> ProductPrices { get; set; }
}

public class ProductPrice
{
public double Price{ get; set; }
}


And I want to map it to the following Dto

public class ProductDto
{
public name Name{ get; set; }
public double UnitSize { get; set; }
public int ItemsPerPack { get; set; }
public double Price{ get; set; }
}


I have read into using AutoMapper for this, but am unsure how to setup the configuration because there would be 4 sources mapping to one destination, all from lists. I would expect to there to be multiple items with the same property values and that is desired. Do I have to ForMember<> map for each item?

Answer

You can do it in a Custom Type Converter:

Func<Products, IEnumerable<ProductDto>> conversion = product => 
    from size in product.ProductSizes
    from package in size.ProductPackages
    from price in package.ProductPrices
    select new ProductDto {
        Name = product.Name,
        UnitSize = size.UnitSize,
        ItemsPerPack = package.ItemsPerPack,
        Price = price.Price
    };

Mapper.Initialize(c => c.CreateMap<Products, IEnumerable<ProductDto>>()
                        .ConvertUsing(conversion));  


var product = GetProduct(…);
var dtos = Mapper.Map<Products, IEnumerable<ProductDto>>(product);
Comments