Automapper 4.2 IgnoreAllNonExisting – ignore missing properties

Given that Automapper 4.2 has marked the static API as obsolete we shouldn’t be using things like Mapper.GetAllTypes() etc. as they will be removed in version 5. A 4.2+ version of a popular extension method for ignoring properties which exist on the destination type but not on the source type is below:

public static IMappingExpression<TSource, TDestination> 
    IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
    foreach(var property in expression.TypeMap.GetUnmappedPropertyNames())
    {
        expression.ForMember(property, opt => opt.Ignore());
    }

    return expression;
}
 

2 thoughts on “Automapper 4.2 IgnoreAllNonExisting – ignore missing properties”

  1. Hello, Thanks for the code.
    I have written a generic method for mapping.
    public static D Map(S uiSource, D destination) where D : class, new()
    {

    MapperConfiguration config = new MapperConfiguration(cfg =>
    {
    cfg.CreateMap
    ().IgnoreAllNonExisting();
    });
    IMapper mapper = config.CreateMapper();
    destination = mapper.Map
    (uiSource);
    return destination;
    }
    public static IMappingExpressionIgnoreAllNonExisting(this IMappingExpression expression)
    {
    foreach (var property in expression.TypeMap.GetUnmappedPropertyNames())
    {
    expression.ForMember(property, opt => opt.Ignore());
    }

    return expression;
    }
    But this is not working

Leave a Reply

Your email address will not be published. Required fields are marked *