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

如何验证AutoMapper中复杂对象内的源属性未映射问题

AutoMapper检测未映射的嵌套源属性配置方案

你的核心需求是让AssertConfigurationIsValid()检测到Source.Inner.Value2未被映射并抛出错误,原代码存在两个关键问题:

  • 连续调用ValidateMemberList会覆盖配置,最终仅生效最后一次的MemberList.Source
  • 默认情况下,AutoMapper不会递归检查嵌套类的源成员,只会验证顶层类的成员

要实现需求,需要按以下方式修改配置:

  1. 为嵌套类Inner单独创建映射规则,并开启源成员验证
  2. 在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 parameters

Inner -> Inner (Destination member list)
AutomapperTest.Inner -> AutomapperTest.Inner (Destination member list)

Unmapped properties:
Value2

这样就实现了你期望的检测效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 07:54:11