如何使用AutoMapper映射包含子DTO的ProductsDTO到ProductsViewModel?
实现ProductsDTO到ProductsViewModel的自动映射方案
嘿,我来给你分享一个用AutoMapper实现这个自动映射的靠谱方案,这也是.NET生态里处理DTO与ViewModel之间映射最常用的工具,完全能满足你嵌套对象自动映射的需求。
第一步:安装AutoMapper包
首先得确保你的项目里安装了AutoMapper,用以下命令之一即可:
- NuGet包管理器控制台:
Install-Package AutoMapper - .NET CLI命令:
dotnet add package AutoMapper
第二步:完整代码实现
先把你的类定义补全(假设Address相关类有常用属性),然后配置映射并使用:
// 定义DTO类 public class AddressDTO { public string Street { get; set; } public string City { get; set; } public string ZipCode { get; set; } } public class ProductsDTO { public int id; public AddressDTO DeliveryAddress; } // 定义ViewModel类 public class AddressViewModel { public string Street { get; set; } public string City { get; set; } public string ZipCode { get; set; } } public class ProductsViewModel { public int id; public AddressViewModel DeliveryAddress; } // 映射逻辑实现 class Program { static void Main(string[] args) { // 1. 创建AutoMapper配置 var config = new MapperConfiguration(cfg => { // 配置ProductsDTO到ProductsViewModel的映射 cfg.CreateMap<ProductsDTO, ProductsViewModel>(); // 注:因为AddressDTO和AddressViewModel的属性名称/类型完全匹配,AutoMapper会自动处理嵌套映射 // 如果你想更清晰,也可以显式加上这行:cfg.CreateMap<AddressDTO, AddressViewModel>(); }); // 验证配置(可选,但建议加上,能提前发现映射错误) config.AssertConfigurationIsValid(); // 2. 创建映射器实例 var mapper = config.CreateMapper(); // 3. 模拟你的数据源 var productsDtoList = new List<ProductsDTO> { new ProductsDTO { id = 1, DeliveryAddress = new AddressDTO { Street = "5th Avenue", City = "New York", ZipCode = "10011" } }, new ProductsDTO { id = 2, DeliveryAddress = new AddressDTO { Street = "Hollywood Blvd", City = "Los Angeles", ZipCode = "90028" } } }; // 4. 执行映射(用你示例里的ForEach方式) productsDtoList.ForEach(dto => { var productViewModel = mapper.Map<ProductsViewModel>(dto); // 这里可以对映射后的ViewModel做后续处理,比如输出或存入集合 Console.WriteLine($"商品ID:{productViewModel.id},配送城市:{productViewModel.DeliveryAddress.City}"); }); } }
关键说明
- AutoMapper默认会匹配同名同类型的字段/属性,包括嵌套对象,所以你的DeliveryAddress嵌套映射完全不需要额外写逻辑;
- 如果后续字段/属性名不一致,只需要在
CreateMap里用ForMember方法指定映射关系即可; AssertConfigurationIsValid()方法可以帮你提前验证映射配置是否有问题,避免运行时出错。
内容的提问来源于stack exchange,提问作者Janani
相关产品推荐
相关产品推荐

