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

如何使用AutoMapper实现嵌套映射?附实体与模型定义

嘿,这个问题我熟,刚好之前做过类似的嵌套映射,给你一步步拆解怎么用AutoMapper搞定它~

使用AutoMapper实现嵌套实体映射的步骤

你的场景里User类包含了Location嵌套实体,要把它映射到UserModel(我默认你的UserModel需要对应的嵌套模型来存地址信息,毕竟总不能丢了位置数据对吧),具体操作如下:

1. 补全对应的模型类

你给出的UserModel只写了开头,我先补全需要的嵌套模型和完整的UserModel(和实体属性一一对应):

public class LocationModel 
{ 
    public string City { get; set; } 
    public string Country { get; set; } 
}

public class UserModel 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public LocationModel Location { get; set; } 
    public string Gender { get; set; } 
    public string Skills { get; set; } 
    public bool IsPrivate { get; set; } // 实体里是驼峰的isPrivate,模型用帕斯卡命名AutoMapper能自动识别大小写差异
}

2. 安装AutoMapper包

先确保项目里装了AutoMapper,用NuGet或.NET CLI都可以:

# NuGet包管理器控制台命令
Install-Package AutoMapper

# 或者.NET CLI命令
dotnet add package AutoMapper

3. 创建映射配置文件

推荐用Profile类管理映射配置,这样更清晰也方便维护:

public class UserMappingProfile : Profile
{
    public UserMappingProfile()
    {
        // 配置User到UserModel的映射
        CreateMap<User, UserModel>();
        
        // 因为Location和LocationModel的属性名称完全一致,AutoMapper会自动处理嵌套映射
        // 要是遇到属性名不一致的情况,才需要单独配置这个映射,比如:
        // CreateMap<Location, LocationModel>()
        //     .ForMember(dest => dest.CityName, opt => opt.MapFrom(src => src.City));
    }
}

4. 初始化AutoMapper

分两种常见场景:

ASP.NET Core依赖注入场景

在Program.cs里注册AutoMapper,传入刚才的Profile类:

var builder = WebApplication.CreateBuilder(args);

// 注册AutoMapper,自动扫描指定类型所在程序集里的Profile
builder.Services.AddAutoMapper(typeof(UserMappingProfile));

// 其他服务注册...

var app = builder.Build();

非依赖注入场景(比如控制台程序)

手动创建配置并初始化Mapper:

var mapperConfig = new MapperConfiguration(cfg =>
{
    cfg.AddProfile<UserMappingProfile>();
});

// 开发环境建议加上这句,验证映射配置是否正确,提前发现问题
mapperConfig.AssertConfigurationIsValid();

var mapper = mapperConfig.CreateMapper();

5. 实际使用映射

现在就可以把User实例映射到UserModel了:

// 构造一个测试用的User实例
var testUser = new User
{
    Id = 1,
    FirstName = "Jane",
    LastName = "Smith",
    Location = new Location { Id = 5, City = "London", Country = "UK" },
    Gender = "Female",
    Skills = "JavaScript, React",
    isPrivate = true
};

// 执行映射
var userModel = mapper.Map<UserModel>(testUser);

// 此时userModel.Location.City就是"London",Country是"UK",其他属性也都完成了正确映射

额外注意点

  • 如果不需要映射某些属性,可以用ForMember指定忽略:比如不想映射Id,就在CreateMap<User, UserModel>()后面加.ForMember(dest => dest.Id, opt => opt.Ignore())(不过你的UserModel里没写Id,所以不用管)。
  • AutoMapper默认会忽略null值,要是需要更严格的映射规则,可以在配置里调整,比如cfg.ForAllMaps((map, exp) => exp.ForAllMembers(opt => opt.Condition((src, dest, srcMember) => srcMember != null)));。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:04:30