如何配置 AutoMapper 在映射时不检查成员列表?

How to configure AutoMapper to not check the member list while mapping?

我正在创建如下所示的地图,同时将成员列表选项传递给 None

CreateMap<Level, LevelVM>(MemberList.None);

但我不想对我创建的每张地图都这样做。我想在全球范围内应用此设置,作为默认设置。有办法实现吗?

默认情况下,AutoMapper 会尝试将源类型的所有属性映射到目标类型。如果某些属性在目标类型中不可用,则在进行映射时不会抛出异常。但是,当您使用 ValidateMapperConfiguration() 时,它会抛出异常。

  class SourceType
    {
        public string Value1 { get; set; }
    }


class DestinationType
{    
    public string Value1{ get; set; }
    public string Value2{ get; set; }
}

AutoMapper.AutoMapperConfigurationException : The following 1 properties on DestinationType are not mapped: Value2 Add a custom mapping expression, ignore, or rename the property on SourceType.

您可以通过全局设置忽略目标类型上不存在的所有属性来覆盖此行为。 你可以像我说的那样设置 class 级别或 属性 级别或全局

只需在 Global.asax

中添加以下代码
Mapper.Initialize(cfg =>
    {
       cfg.ValidateInlineMaps = false
    }

在 属性 处,level 在这两个对象之间进行映射时忽略了 Value2 属性。为此,我们需要使用 AutoMapper Ignore 属性 和

的地址 属性
config.CreateMap<SourceType,DestinationType>()
                    //Ignoring the Value2  property of the destination type
                    .ForMember(dest => dest.Value2 , act => act.Ignore());