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

如何在C#中用AutoMapper映射DataQuantity到Data并覆盖Quantity属性?

解决方案

你遇到的核心问题是AutoMapper默认不会自动映射嵌套对象的属性到目标类,需要显式指定包含嵌套的Data对象属性,再覆盖Quantity字段。

正确的映射配置

修改映射配置,用IncludeMembers让AutoMapper先从DataQuantity.Data中映射匹配属性,再用DataQuantity.Quantity覆盖目标值:

CreateMap<DataQuantity, Data>()
    .IncludeMembers(src => src.Data)
    .ForMember(dest => dest.Quantity, opt => opt.MapFrom(src => src.Quantity));

原理说明

  • IncludeMembers(src => src.Data):告诉AutoMapper,除了匹配DataQuantity自身的属性外,还要从嵌套的src.Data对象中提取Property1、Property2这类同名属性完成映射。
  • ForMember配置:明确指定用DataQuantity自身的Quantity覆盖目标Data的对应字段,此配置优先级高于IncludeMembers的映射规则。

完整可运行示例

// 定义实体类
public class Data
{
    public string? Property1 { get; set; }
    public string? Property2 { get; set; }
    public int Quantity { get; set; } = 1;
}

public class DataQuantity
{
    public Data Data { get; set; } = null!;
    public int Quantity { get; set; } = 1;
}

// 配置AutoMapper
var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<DataQuantity, Data>()
        .IncludeMembers(src => src.Data)
        .ForMember(dest => dest.Quantity, opt => opt.MapFrom(src => src.Quantity));
});

// 测试映射
var dataQty = new DataQuantity
{
    Data = new Data { Property1 = "示例值1", Property2 = "示例值2", Quantity = 5 },
    Quantity = 20
};

var mapper = config.CreateMapper();
var mappedData = mapper.Map<Data>(dataQty);

// 最终结果:Property1="示例值1",Property2="示例值2",Quantity=20

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 05:22:20