Reputation: 5323
I have a rather large object with lots of properties.
I am using Automapper to map to the properties from a grid.
Only a few of the properties need to be mapped and the rest have to be ignored as they are used later not at the time of mapping
Is there a way to 'Ignore' all of these properties or do I need to write an explicit 'Ignore' for every property - see code below. I'd like to be able to '.IgnoreAllNotUsed' instead of having to ignore one by one. Is this possible?
The class inherits from another class but most of the properties are on the actual class itself
link to picture of code
Upvotes: 2
Views: 2282
Reputation: 4315
Just ignore all properties and then specify ForMember. Here is example:
var mapping = Mapper.CreateMap<Source, Destination>();
mapping.ForAllMembers(opt=>opt.Ignore());
mapping.ForMember(...)
.ForMember(...);
Upvotes: 8
Reputation: 174427
You can use this extension method:
public static void ForAllUnmappedMembers<TSource, TDestination>(
this IMappingExpression<TSource, TDestination> mapping,
Action<IMemberConfigurationExpression<TSource>> memberOptions)
{
var typeMap = Mapper.FindTypeMapFor<TSource, TDestination>();
foreach(var memberName in typeMap.GetUnmappedPropertyNames())
mapping.ForMember(memberName, memberOptions);
}
Use it like this:
Mapper.CreateMap<Source, Destination>()
.ForMember(...)
.ForAllUnmappedMembers(o => o.Ignore());
I haven't tested it but it should work.
Upvotes: 4