使用 Automapper 的嵌套映射

问题描述 投票:0回答:1

我有以下课程:

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

我想使用 Automapper 从 Product 映射到 ProductWithPricesResponse,但我不知道如何在 Product 的 ProductPrices 列表到 ProductWithPricesResponse 的 ProductPriceResponsepero 列表之间进行嵌套映射。

我在我的 ProductProfile 中试过这个:

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

我想做的是,首先告诉 Automapper 我要从 Product 映射到 ProductWithPricessResponse,然后在 Product Prices 列表中,将 ProductPrice 的每一项转换为 ProductPriceResponse 的一项,但我收到一个错误提示我不能隐式地将 ProductPriceResponse 的通用列表转换为 ProductWithPricesresponse 的对象。

有人已经做过这种类型的嵌套映射,可以帮助我吗?

c# automapper
1个回答
0
投票

需要为每个要映射的类配置一个映射:

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

那么它应该开箱即用。

© www.soinside.com 2019 - 2024. All rights reserved.