Automapper v5 Ignore unmapped properties

2019-04-06 15:14发布

问题:

Previously when I used Automapper v3.x ignoring unmapped properties could be done by simply adding a .IgnoreUnmappedProperties() extension which looked like this

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;
    }
}

How can this extension be rewritten to work with Version 5.x. I can of course add the following to each property.

.ForMember(dest => dest.LastUpdatedBy, opt => opt.Ignore())

or not call

Mapper.AssertConfigurationIsValid();

回答1:

You can do that using the new CreateMap method parameter, and specify the validation that you want.

CreateMap<TSource, TDestination>(MemberList.None)

The MemberList.None should do the trick. You can also switch between the source or destination validations.

Automapper - Selecting members to validate