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();
Kian
  • 1,319
  • 1
  • 13
  • 23
MartinS
  • 6,134
  • 10
  • 34
  • 40
  • The solution for AutoMapper 11 is https://stackoverflow.com/questions/72367321/automapper-map-a-few-and-ignore-the-rest/73333328#73333328 – Michael Freidgeim Jan 06 '23 at 18:36

1 Answers1

12

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

MarredCheese
  • 17,541
  • 8
  • 92
  • 91
Ahmed IG
  • 563
  • 7
  • 17
  • 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. – HellBaby Aug 09 '22 at 16:47