automapperautomapper-5

Automapper v5 Ignore unmapped properties


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();

Solution

  • You can do that using the CreateMap method's memberList parameter to 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