Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore all destination members, except the ones that are mapped? [duplicate]

Tags:

c#

automapper

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(); 
like image 921
epitka Avatar asked Dec 06 '10 14:12

epitka


People also ask

How do you ignore fields in Mapper?

We can ignore unmapped properties in several mappers by setting the unmappedTargetPolicy via @MapperConfig to share a setting across several mappers.

How do I ignore someone on AutoMapper?

Automapper ignores property using 'DoNotValidate' Using DoNotValidate will Ignore the current member when validating source members.

How do I ignore property mapping in AutoMapper?

So, the AutoMapper Ignore() method is used when you want to completely ignore the property in the mapping. The ignored property could be in either the source or the destination object.


1 Answers

This is working for me:

public static class MappingExpressionExtensions {     public static IMappingExpression<TSource, TDest> IgnoreAllUnmapped<TSource, TDest>(this IMappingExpression<TSource, TDest> expression)     {         expression.ForAllMembers(opt => opt.Ignore());         return expression;     } } 

Because ForAllMembers returns void, calling ForAllMembers(o => o.Ignore()) without this extension method wouldn't work. We want to keep the mapping expression available to enable the subsequent mappings:

CreateMap<Source, Destination>()             .IgnoreAllUnmapped()             .ForMember(d => d.Text, o => o.MapFrom(s => s.Name))             .ForMember(d => d.Value, o => o.MapFrom(s => s.Id)); 
like image 143
CodeMonkeyKing Avatar answered Oct 03 '22 23:10

CodeMonkeyKing