Ignore mapping one property with Automapper
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/
Msam85
Updated on October 05, 2021Comments
-
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 over 12 yearsThe ignore attribute leaks auto-mapper through your application though.
-
Redeemed1 almost 12 yearsDoes automapper have a ForSourceMember extension?
-
Pawel Krakowiak over 11 yearsAutoMapper is one thing which I don't mind leaking all over the place. ;)
-
Tom Stickel about 11 yearsI do this currently, but it would be ideal to NOT have to create all these Ignore... :/
-
Alapago about 10 yearsYou can always consider deriving
IgnoreMapAttribute
. -
Sam I am says Reinstate Monica over 9 yearsdo you know if there's a way to ignore when actually doing the mapping and not when creating the map?
-
Shog9 over 9 yearsFYI: merged from stackoverflow.com/questions/4052579/…
-
Shog9 over 9 yearsFYI: merged from stackoverflow.com/questions/4052579/…
-
Lski over 9 yearsI 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 over 8 yearsTHIS is what I came looking for, so useful when only modifying a subset of domain object properties from a much simpler DTO.
-
Ristogod over 7 yearsThis 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. over 7 yearsFor 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 about 7 yearsRegarding
params
: You could return an array of selectors from inside a single lambda, then map over each selector withforeach
orSelect()
Perhaps not less messy-looking, though. -
Chase Florell about 6 yearsThis 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 about 6 yearsAlso,
CreateMap<Foo, Bar>().ForSourceMember(x => x.Blarg, opt => opt.Ignore());
might be useful -
Bassie about 6 yearsI just get
'Mapper' does not contain a definition for 'GetAllTypeMaps' [DSSTools]
.. -
Piotr M almost 6 yearsThis is the answer kids, make that official so newbies won't be confused
-
Mike Bovenlander over 5 years@Bassie Use
Mapper.Configuration.GetAllTypeMaps()
source -
monty over 5 years@stackoverfloweth Don't you mean:
CreateMap<SourceType, DestType> (MemberList.Source).ForSourceMember(x => x.MySourceProperty, opt => opt.DoNotValidate())
? -
Jamie over 5 yearsIgnore has been replaced with DoNotValidate in ForSourceMember: github.com/AutoMapper/AutoMapper/blob/master/docs/…
-
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 forIgnore
was made on theISourceMemberConfigurationExpression
interface but not on the disjointIMemberConfigurationExpression`3
interface. -
Franva about 5 years@stackoverfloweth what are the differences between ForSourceMember() and ForMember()?
-
rvnlord almost 5 years@Franva ForMember() is actually "ForDestinationMember()"
-
fiorebat over 4 yearsIts
[IgnoreMap]
fromIgnoreMapAttribute
-
Jason Dias over 4 yearsfor 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 over 4 yearsthanks @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 over 3 years
Ignore()
is not present onForSourceMember()
extension. as @JasonDias says, it should beDoNotValidate()
. At least in latest version of automapper. -
serge about 3 yearsHow does it work for
ReverseMap
? ReverseMap().ForPath(... -
Suncat2000 about 3 yearsI think I'd prefer to name it
IgnoreMember()
, but great extension! -
Alexander over 2 yearsSeems 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 over 2 years
IgnoreMap
was Removed. docs.automapper.org/en/latest/…