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

AutoMapper v8升级至9.0+:静态转IMapper实例实现对象自映射

AutoMapper v9+ 实例化映射替代静态Mapper方案

AutoMapper v9+ 废弃了静态Mapper类,需要改用IMapper实例完成映射。针对你代码中把实体映射到模型自身属性的场景,可按以下方式改造:

1. 完成AutoMapper的注册与配置

首先创建映射配置类,定义ConfigEntity到ConfigModel的映射规则:

public class ConfigProfile : Profile
{
    public ConfigProfile()
    {
        CreateMap<ConfigEntity, ConfigModel>();
    }
}

在依赖注入容器中注册AutoMapper(以ASP.NET Core为例):

services.AddAutoMapper(typeof(ConfigProfile));

2. 改造ConfigModel类的Load方法

根据ConfigModel的创建方式,选择以下两种方案:

方案一:构造注入IMapper(适合DI管理的类)

如果ConfigModel由依赖注入容器创建,直接通过构造函数注入IMapper实例:

public class ConfigModel 
{
    private readonly IMapper _mapper;

    public ConfigModel(IMapper mapper)
    {
        _mapper = mapper;
    }

    public int MyProperty1 { get; set; }
    // ... 其他属性

    public ConfigModel Load(ConfigEntity config)
    {
        _mapper.Map(config, this);
        return this;
    }
}

方案二:Load方法传入IMapper(适合手动实例化的类)

如果ConfigModel是手动new出来的,可将IMapper作为Load方法的参数传入:

public class ConfigModel 
{
    public int MyProperty1 { get; set; }
    // ... 其他属性

    public ConfigModel Load(ConfigEntity config, IMapper mapper)
    {
        mapper.Map(config, this);
        return this;
    }
}

注意事项

  • 两种方案的核心都是调用IMapper.Map(source, destination)方法,实现将源实体的属性值映射到目标实例(当前ConfigModel对象)上,和原静态Mapper.Map的功能完全一致。
  • 确保所有映射规则都已在Profile类中定义,否则映射会失败。

内容的提问来源于stack exchange,提问作者Sreejith K.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 03:15:43