有没有办法告诉AutoMapper忽略除明确映射的属性之外的所有属性?
我有外部DTO类可能会从外部更改,我想避免指定要显式忽略的每个属性,因为添加新属性会在尝试将它们映射到我自己的对象时破坏功能(导致异常).
以前当我使用Automapper v3.x时,忽略未映射的属性可以通过简单地添加一个.IgnoreUnmappedProperties()看起来像这样的扩展来完成
public static class AutoMapperExtensions
{
public static IMappingExpression<TSource, TDestination> IgnoreUnmappedProperties<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
var typeMap = Mapper.FindTypeMapFor<TSource, TDestination>();
if (typeMap != null)
{
foreach (var unmappedPropertyName in typeMap.GetUnmappedPropertyNames())
{
expression.ForMember(unmappedPropertyName, opt => opt.Ignore());
}
}
return expression;
}
}
Run Code Online (Sandbox Code Playgroud)
如何重写此扩展以与V5.x一起使用.我当然可以为每个属性添加以下内容.
.ForMember(dest => dest.LastUpdatedBy, opt => opt.Ignore())
Run Code Online (Sandbox Code Playgroud)
或不打电话
Mapper.AssertConfigurationIsValid();
Run Code Online (Sandbox Code Playgroud)