You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用AutoMapper映射ProductRequest为Product并生成ProductPrice实例

问题描述

我在Product控制器中有如下POST请求:

[HttpPost("/product")]
public async Task<IActionResult> CreateProduct([FromBody] ProductRequest productCreate)
{
    var response = await _productService.CreateProduct(_mapper.Map<Product>(productCreate));
    return Ok(_mapper.Map<ProductResponse>(response));
}

ProductRequest结构:

public class ProductRequest
{
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal? Price { get; set; }
}

需要用AutoMapper将ProductRequest映射为Product对象,Product结构:

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

已知Name、Description的基础映射规则,不清楚如何利用ProductRequest.Price创建ProductPrice实例。ProductPrice结构:

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

要求映射后的Product包含一个新的ProductPrice对象,其Price值等于ProductRequest.Price的值。

解决方案

通过自定义AutoMapper的映射规则即可实现需求,步骤如下:

1. 创建AutoMapper配置Profile

新建一个继承自Profile的映射配置类,在其中配置完整的映射规则:

public class ProductProfile : Profile
{
    public ProductProfile()
    {
        CreateMap<ProductRequest, Product>()
            // 基础属性映射
            .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name))
            .ForMember(dest => dest.Description, opt => opt.MapFrom(src => src.Description))
            // 处理Prices集合的自定义映射
            .ForMember(dest => dest.Prices, opt => opt.MapFrom(src => 
                src.Price.HasValue 
                    ? new List<ProductPrice>
                    {
                        new ProductPrice
                        {
                            Price = src.Price.Value,
                            StartDate = DateTime.UtcNow, // 可根据业务需求调整起始时间
                            EndDate = null // 设为null表示当前生效价格
                        }
                    }
                    : new List<ProductPrice>()));
    }
}

2. 注册AutoMapper到依赖注入

在Program.cs(.NET 6+)中注册AutoMapper:

builder.Services.AddAutoMapper(typeof(ProductProfile));

3. 验证映射效果

当控制器中调用_mapper.Map<Product>(productCreate)时:

  • 如果productCreate.Price有值,Product.Prices会包含一个ProductPrice实例,Price为传入值,StartDate设为当前UTC时间,EndDate为null;
  • 如果productCreate.Price为null,Prices会是一个空列表。

注:ProductId和Id属于数据库自增字段,无需在映射阶段设置,通常由EF Core在保存时自动生成。

内容的提问来源于stack exchange,提问作者iMSn20

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 14:10:12