Automapper: use default mapping for all other members

Viewed 1696

I have a lot of classes to map from IDataReader like this:

class Dest
{
   public string Field1;
   public string Field2;
   public string Field3;
}

...

public DestProfile
{
   CreateMap<IDataReader, Dest>()
     .ForMember(d => d.Field1, opt => opt.MapFrom(/*Do some custom convertion here*/)
     .ForAllOtherMembers(/*Do default convention-based mapping for all other members/*)
}

So i'd like to perform custom convertion on selected fields and do default mapping without explicitly coding.

Question looks very common, but I didn't find how to achieve this.

1 Answers

So the most straightforward way is to write like this:

.ForAllOtherMembers(opt => opt.MapFrom(src => src[opt.DestinationMember.Name]))

But there are some caveats. For example

.IncludeBase<IDataReader, Base>()
.ForAllOtherMembers(opt => opt.MapFrom(src => src[opt.DestinationMember.Name]))

Here ForAllOtherMembers will override your base class definition.

Related