Automapper v5 Ignore unmapped properties
Asked Answered
P

1

9

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();
Pagas answered 11/10, 2016 at 9:58 Comment(1)
The solution for AutoMapper 11 is #72367821Jointworm
B
13

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

Berey answered 23/11, 2016 at 5:46 Comment(1)
This approach is actually pretty bad as you will end up with invalid mappings. By default, it's targeting the destination, so I would consider it multiple times before changing that behavior.Hypermeter

© 2022 - 2024 — McMap. All rights reserved.