Automapper:对所有其他成员使用默认映射

Automapper: use default mapping for all other members

我有很多 类 可以像这样从 IDataReader 映射:

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/*)
}

所以我想对选定的字段执行自定义转换并在不显式编码的情况下进行默认映射。

问题看起来很常见,但我没有找到如何实现这个问题。

所以最直接的写法就是这样写:

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

但有一些注意事项。例如

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

此处 ForAllOtherMembers 将覆盖您的基本 class 定义。