This question already has an answer here:
- AutoMapper: “Ignore the rest”? 16 answers
Is there a way to do this? We have a SummaryDto that maps from three different types, and when we create a map for each type, props that are not mapped are throwing an error. There are about 35 attributes on the summary dto. To use Ignore() option on each one is just too much trouble. Is there a global ignore? Something like
CreateMap<Source,Target>()
.IgnoreAllUnmapped();
This is working for me:
Because
ForAllMembers
returnsvoid
, callingForAllMembers(o => o.Ignore())
without this extension method wouldn't work. We want to keep the mapping expression available to enable the subsequent mappings:I struggled with this one for quite a while too, or at least a problem similar to this. I had a class with a lot of properties on it (about 30) and I only wanted to map about 4 of them. It seems crazy to add 26 ignore statements (especially when it means that future changes to the class will mean having to update them!)
I finally found that I could tell AutoMapper to ignore everything, and then explicitly add the ones that I did want.
You'd be forgiven for thinking that you could just do this (but don't because it wont compile):
The reason why this doesn't work is that the ForAllMembers() method doesn't support the fluent style of chaining (at least in the current version 2.0).
The good news is that the non-chaining version does indeed work. The one caveat of course is that you need to explicitly tell AutoMapper which members to map. I haven't yet found an easy way to have it both ways so that you can still use the implied mappings and ignore the broken ones.
Extension method which allows fluent syntax for the ForAllMembers method:
Usage:
The call to IgnoreAllMembers must be before the call to ForMember.
Try to use
.ConvertUsing()
in your case, e.g.So, you can describe all properties what you want to have in your object, other will be ignored.
To avoid having to explicitly specify the mapped properties, you can use IgnoreAllNonExisting. It ignores any destination properties that don't have mapped source properties.