我正在创建如下所示的 map ,同时将成员列表选项传递给None
:
CreateMap<Level, LevelVM>(MemberList.None);
但我不想为我创建的每张 map 都这样做。我希望将此设置作为默认值全局应用。有没有办法实现这个目标?
最佳答案
默认情况下,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.
您可以通过将全局设置设置为忽略目标类型上不存在的所有属性来覆盖此行为。 您可以像我所说的那样在类级别或属性级别或全局上进行设置
只需在 Global.asax 中添加以下代码即可
Mapper.Initialize(cfg =>
{
cfg.ValidateInlineMaps = false
}
在属性上,level 在这两个对象之间进行映射时会忽略 Value2 属性。为此,我们需要使用 AutoMapper Ignore 属性和 Address 属性
config.CreateMap<SourceType,DestinationType>()
//Ignoring the Value2 property of the destination type
.ForMember(dest => dest.Value2 , act => act.Ignore());
关于c# - 如何配置 AutoMapper 在映射时不检查成员列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56431277/