AutoMapper: "Ignore the rest"?

Viewed 98985

Is there a way to tell AutoMapper to ignore all of the properties except the ones which are mapped explicitly?

I have external DTO classes which are likely to change from the outside and I want to avoid specifying each property to be ignored explicitly, since adding new properties will break the functionality (cause exceptions) when trying to map them into my own objects.

19 Answers

How would you prefer to specify that certain members be ignored? Is there a convention, or base class, or attribute you would like to apply? Once you get into the business of specifying all the mappings explicitly, I'm not sure what value you'd get out of AutoMapper.

By default, AutoMapper uses the destination type to validate members but you can skip validation by using MemberList.None option.

var configuration = new MapperConfiguration(cfg =>
  cfg.CreateMap<Source2, Destination2>(MemberList.None);
);

You can find the reference here

In a WebApi for dotnet 5, using the Nuget package AutoMapper.Extensions.Microsoft.DependencyInjection, I'm doing it like this in a mapper profile. I'm really rusty with AutoMapper, but it seems to work fine now for unmapped members.

In Startup:

var mapperConfig = new MapperConfiguration(mc => mc.AddProfile(new AutoMapperProfile()));
    services.AddSingleton(mapperConfig.CreateMapper());

and in my AutoMapperProfile:

CreateMap<ProjectActivity, Activity>()
        .ForMember(dest => dest.ActivityName, opt => opt.MapFrom(src => src.Name))
        .ValidateMemberList(MemberList.None);

The only infromation about ignoring many of members is this thread - http://groups.google.com/group/automapper-users/browse_thread/thread/9928ce9f2ffa641f . I think you can use the trick used in ProvidingCommonBaseClassConfiguration to ignore common properties for similar classes.
And there is no information about the "Ignore the rest" functionality. I've looked at the code before and it seems to me that will be very and very hard to add such functionality. Also you can try to use some attribute and mark with it ignored properties and add some generic/common code to ignore all marked properties.

The current (version 9) solution for ignoring the properties that do not exist in the destination type is to create a flipped mapping and reversing it:

var config = new MapperConfiguration(cfg => {
  cfg.CreateMap<TheActualDestinationType, TheActualSourceType>().ReverseMap();
});
Related