Ignore mapping one property with Automapper

276,472

Solution 1

From Jimmy Bogard: CreateMap<Foo, Bar>().ForMember(x => x.Blarg, opt => opt.Ignore());

It's in one of the comments at his blog.

UPDATE(from Jamie's comment Jan 4 '19 at 11:11:)

Ignore has been replaced with DoNotValidate in ForSourceMember: https://github.com/AutoMapper/AutoMapper/blob/master/docs/8.0-Upgrade-Guide.md

Solution 2

I'm perhaps a bit of a perfectionist; I don't really like the ForMember(..., x => x.Ignore()) syntax. It's a little thing, but it matters to me. I wrote this extension method to make it a bit nicer:

public static IMappingExpression<TSource, TDestination> Ignore<TSource, TDestination>(
    this IMappingExpression<TSource, TDestination> map,
    Expression<Func<TDestination, object>> selector)
{
    map.ForMember(selector, config => config.Ignore());
    return map;
}

It can be used like so:

Mapper.CreateMap<JsonRecord, DatabaseRecord>()
        .Ignore(record => record.Field)
        .Ignore(record => record.AnotherField)
        .Ignore(record => record.Etc);

You could also rewrite it to work with params, but I don't like the look of a method with loads of lambdas.

Solution 3

You can do this:

conf.CreateMap<SourceType, DestinationType>()
   .ForSourceMember(x => x.SourceProperty, y => y.Ignore());

Or, in latest version of Automapper, you simply want to tell Automapper to not validate the field

conf.CreateMap<SourceType, DestinationType>()
   .ForSourceMember(x => x.SourceProperty, y => y.DoNotValidate());

Solution 4

There is now (AutoMapper 2.0) an IgnoreMap attribute, which I'm going to use rather than the fluent syntax which is a bit heavy IMHO.

Solution 5

Just for anyone trying to do this automatically, you can use that extension method to ignore non existing properties on the destination type :

public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
    var sourceType = typeof(TSource);
    var destinationType = typeof(TDestination);
    var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType.Equals(sourceType)
        && x.DestinationType.Equals(destinationType));
    foreach (var property in existingMaps.GetUnmappedPropertyNames())
    {
        expression.ForMember(property, opt => opt.Ignore());
    }
    return expression;
}

to be used as follow :

Mapper.CreateMap<SourceType, DestinationType>().IgnoreAllNonExisting();

thanks to Can Gencer for the tip :)

source : http://cangencer.wordpress.com/2011/06/08/auto-ignore-non-existing-properties-with-automapper/

Share:
276,472
Msam85
Author by

Msam85

Updated on October 05, 2021

Comments

  • Msam85
    Msam85 over 2 years

    I'm using Automapper and I have the following scenario: Class OrderModel has a property called 'ProductName' that isn't in the database. So when I try to do the mapping with:

    Mapper.CreateMap<OrderModel, Orders>(); 
    

    It generates an exception :

    "The following 1 properties on Project.ViewModels.OrderModel are not mapped: 'ProductName'

    I've read at AutoMapper's Wiki for Projections the opposite case (the extra attribute is on the destination, not in the source which is actually my case )

    How can I avoid automapper to make the mapping of this property?

  • Phill
    Phill over 12 years
    The ignore attribute leaks auto-mapper through your application though.
  • Redeemed1
    Redeemed1 almost 12 years
    Does automapper have a ForSourceMember extension?
  • Pawel Krakowiak
    Pawel Krakowiak over 11 years
    AutoMapper is one thing which I don't mind leaking all over the place. ;)
  • Tom Stickel
    Tom Stickel about 11 years
    I do this currently, but it would be ideal to NOT have to create all these Ignore... :/
  • Alapago
    Alapago about 10 years
    You can always consider deriving IgnoreMapAttribute.
  • Sam I am says Reinstate Monica
    Sam I am says Reinstate Monica over 9 years
    do you know if there's a way to ignore when actually doing the mapping and not when creating the map?
  • Shog9
    Shog9 over 9 years
  • Shog9
    Shog9 over 9 years
  • Lski
    Lski over 9 years
    I know this goes beyond the initial question but I really like this answer, its clean, very easy to read and instantly understand plus easy to reuse
  • Adam Tolley
    Adam Tolley over 8 years
    THIS is what I came looking for, so useful when only modifying a subset of domain object properties from a much simpler DTO.
  • Ristogod
    Ristogod over 7 years
    This doesn't work when injecting IMapper. Mapper.GetAllTypeMaps doesn't exist in the latest version of AutoMapper. Additionally, when I setup my maps in an AutoMapper.Profile and then subsequently injected IMapper, I got this exception "Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance."
  • Rob S.
    Rob S. over 7 years
    For the scenario given in the question, this should be the accepted answer. The current accepted answer ignores mapping of properties in the destination object. This question is asking about ignoring mappings in the source object.
  • jpaugh
    jpaugh about 7 years
    Regarding params: You could return an array of selectors from inside a single lambda, then map over each selector with foreach or Select() Perhaps not less messy-looking, though.
  • Chase Florell
    Chase Florell about 6 years
    This is a good way to ignore a base property that is inherited across many objects. Saves from having to ignore it in every mapping config.
  • stackoverfloweth
    stackoverfloweth about 6 years
    Also, CreateMap<Foo, Bar>().ForSourceMember(x => x.Blarg, opt => opt.Ignore()); might be useful
  • Bassie
    Bassie about 6 years
    I just get 'Mapper' does not contain a definition for 'GetAllTypeMaps' [DSSTools] ..
  • Piotr M
    Piotr M almost 6 years
    This is the answer kids, make that official so newbies won't be confused
  • Mike Bovenlander
    Mike Bovenlander over 5 years
    @Bassie Use Mapper.Configuration.GetAllTypeMaps() source
  • monty
    monty over 5 years
    @stackoverfloweth Don't you mean: CreateMap<SourceType, DestType> (MemberList.Source).ForSourceMember(x => x.MySourceProperty, opt => opt.DoNotValidate()) ?
  • Jamie
    Jamie over 5 years
    Ignore has been replaced with DoNotValidate in ForSourceMember: github.com/AutoMapper/AutoMapper/blob/master/docs/…
  • smartcaveman
    smartcaveman over 5 years
    @Jamie @monty - I started to update this re: your comment, but it looks like the syntax change only affects the projection case (where the source property needs to be ignored). The OP's request is to ignore a destination property, so, Ignore() remains the correct syntax. This is because the syntax change for Ignore was made on the ISourceMemberConfigurationExpression interface but not on the disjoint IMemberConfigurationExpression`3 interface.
  • Franva
    Franva about 5 years
    @stackoverfloweth what are the differences between ForSourceMember() and ForMember()?
  • rvnlord
    rvnlord almost 5 years
    @Franva ForMember() is actually "ForDestinationMember()"
  • fiorebat
    fiorebat over 4 years
    Its [IgnoreMap] from IgnoreMapAttribute
  • Jason Dias
    Jason Dias over 4 years
    for anyone who is looking for extension method public static IMappingExpression<TSource, TDestination> IgnoreSourceValidation<TSource, TDestination>( this IMappingExpression<TSource, TDestination> map, Expression<Func<TSource, object>> selector) { map.ForSourceMember(selector, config => config.DoNotValidate()); return map; }
  • Jason Dias
    Jason Dias over 4 years
    thanks @Steve Rukuts, for anyone who is looking for extension method to ignore source members you can use this public static IMappingExpression<TSource, TDestination> IgnoreSourceValidation<TSource, TDestination>( this IMappingExpression<TSource, TDestination> map, Expression<Func<TSource, object>> selector) { map.ForSourceMember(selector, config => config.DoNotValidate()); return map; }
  • DLeh
    DLeh over 3 years
    Ignore() is not present on ForSourceMember() extension. as @JasonDias says, it should be DoNotValidate(). At least in latest version of automapper.
  • serge
    serge about 3 years
    How does it work for ReverseMap? ReverseMap().ForPath(...
  • Suncat2000
    Suncat2000 about 3 years
    I think I'd prefer to name it IgnoreMember(), but great extension!
  • Alexander
    Alexander over 2 years
    Seems like Ignore() does not work (I am getting destination field overwritten with default value if such field is missing in source) if I map collection to collection, not entity to entity.
  • Mohammad Roshani
    Mohammad Roshani over 2 years
    IgnoreMap was Removed. docs.automapper.org/en/latest/…