使用AutoMapper将对象属性映射为字典时遇未映射成员错误
问题:使用AutoMapper将对象映射为字典时出现未映射成员错误
需求是将对象的每个属性转换为字典的键值对(如Book对象的Id和Name属性对应字典的id、name键),但运行代码时触发以下错误:
Unmapped members were found. Review the types and members below. Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type For no matching constructor, add a no-arg ctor, add optional arguments, or map all of the constructor parameters ======================================================================================================================================================================================================================================================================= Book -> Dictionary`2 (Destination member list) Book -> System.Collections.Generic.Dictionary`2[[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]] (Destination member list) Unmapped properties: Keys Values Item
用户的实现代码:
using AutoMapper; var book = new Book() { Id = 1, Name = "A" }; IMapper mapper = new Mapper(new MapperConfiguration( config => config.CreateMap<Book, Dictionary<string, string>>() .ConstructUsing((source, dest) => new Dictionary<string, string>() { { "id", source.Id.ToString() }, {"name", source.Name} }))); mapper.ConfigurationProvider.AssertConfigurationIsValid(); var bookData = new Dictionary<string, string>(); mapper.Map(book, bookData); public class Book { public int Id { get; set; } public string Name { get; set; } }
错误原因
AutoMapper在执行AssertConfigurationIsValid()时,会检查目标类型(Dictionary<string,string>)的所有公共成员(Keys、Values、Item),但源类型Book没有对应的属性,因此触发未映射成员的验证错误。
解决方案
方案1:忽略未映射的成员
在映射配置中添加.ForAllOtherMembers(opt => opt.Ignore()),告诉AutoMapper忽略所有未明确映射的成员:
IMapper mapper = new Mapper(new MapperConfiguration( config => config.CreateMap<Book, Dictionary<string, string>>() .ConstructUsing((source, dest) => new Dictionary<string, string>() { { "id", source.Id.ToString() }, {"name", source.Name} }) .ForAllOtherMembers(opt => opt.Ignore())));
方案2:使用ConvertUsing定义完整转换逻辑
ConvertUsing可以直接定义从源对象到目标字典的转换规则,AutoMapper会跳过成员映射验证,完全遵循你定义的逻辑:
IMapper mapper = new Mapper(new MapperConfiguration( config => config.CreateMap<Book, Dictionary<string, string>>() .ConvertUsing(source => new Dictionary<string, string>() { { "id", source.Id.ToString() }, {"name", source.Name} })));
同时可以简化字典的创建方式,直接通过mapper.Map生成目标字典,无需提前实例化:
var bookData = mapper.Map<Dictionary<string, string>>(book);
内容的提问来源于stack exchange,提问作者Thiago
相关产品推荐
相关产品推荐

