如何验证AutoMapper中复杂对象内的源属性未映射问题
AutoMapper检测未映射的嵌套源属性配置方案
你的核心需求是让AssertConfigurationIsValid()检测到Source.Inner.Value2未被映射并抛出错误,原代码存在两个关键问题:
- 连续调用
ValidateMemberList会覆盖配置,最终仅生效最后一次的MemberList.Source - 默认情况下,AutoMapper不会递归检查嵌套类的源成员,只会验证顶层类的成员
要实现需求,需要按以下方式修改配置:
- 为嵌套类
Inner单独创建映射规则,并开启源成员验证 - 在
Source到Target的映射中显式关联Inner.Value1与Target.InnerValue1,同时开启源成员验证,确保AutoMapper能追踪到嵌套类的映射状态
修改后的完整代码如下:
using AutoMapper; namespace AutomapperTest { internal class Program { static void Main(string[] args) { var mapperConfiguration = new MapperConfiguration(c => { // 为Inner类创建映射,开启源成员验证 c.CreateMap<Inner, Inner>() .ValidateMemberList(MemberList.Source); // Source到Target的映射,显式映射Inner.Value1到InnerValue1,同时开启源成员验证 c.CreateMap<Source, Target>() .ForMember(dest => dest.InnerValue1, opt => opt.MapFrom(src => src.Inner.Value1)) .ValidateMemberList(MemberList.Source); }); // 执行配置验证,此时会检测到Inner.Value2未被映射并抛出错误 mapperConfiguration.AssertConfigurationIsValid(); } } class Source { public Inner Inner { get; set; } } class Inner { public string Value1 { get; set; } public string Value2 { get; set; } } class Target { public string InnerValue1 { get; set; } } }
执行上述代码后,AssertConfigurationIsValid()会抛出类似如下的错误:
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 parametersInner -> Inner (Destination member list)
AutomapperTest.Inner -> AutomapperTest.Inner (Destination member list)Unmapped properties:
Value2
这样就实现了你期望的检测效果。
内容的提问来源于stack exchange,提问作者Bohdan
相关产品推荐
相关产品推荐

