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

如何用AutoMapper忽略源属性EnterpriseId并为目标CompanyId赋值?

解决方案

1. 修复AutoMapper映射配置

你的映射配置里ForSourceMember(x => x.EnterpriseId, opt => opt.DoNotValidate())不是正确的忽略方式,应该改用Ignore()来跳过源属性的映射。同时确保配置类正确继承自AutoMapper的Profile:

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<ProductUnitMaster, ProductUnit>()
            // 忽略源对象的EnterpriseId,不参与映射
            .ForSourceMember(src => src.EnterpriseId, opt => opt.Ignore())
            // 目标对象的CompanyId由外部赋值,暂时忽略自动映射
            .ForMember(dest => dest.CompanyId, opt => opt.Ignore());
    }
}

2. 确保AutoMapper服务正确注册

在项目的服务注册环节(比如.NET 6+的Program.cs),要让AutoMapper扫描到你的映射配置类:

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

3. 执行映射代码

你的控制器代码逻辑没问题,但要确保_mapper是通过依赖注入获取的IMapper实例。现在配置正确后,执行以下代码即可完成克隆并赋值CompanyId:

var productUnit = _mapper.Map<ProductUnit>(productUnitMaster, opt =>
    opt.AfterMap((src, dest) => dest.CompanyId = companyData.Id));

4. 排查验证

如果仍然报错,可添加配置验证代码,找出具体配置问题:

// 在初始化或测试环节调用,验证映射配置是否合法
_mapper.ConfigurationProvider.AssertConfigurationIsValid();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 15:50:49