通过ForMember从自定义地图中提取AutoMapper源名称

时间:2011-01-13 19:34:43

标签: c# lambda automapper

我已使用以下代码从现有的Automapper TypeMap成功提取了简单的源/目标对:

private MemberInfo getSource(Type destinationType, string destinationPropertyname)
{
  TypeMap map = Mapper.GetAllTypeMaps()
                      .Where(m => m.DestinationType.Equals(destinationType))
                      .First();
  IEnumerable<PropertyMap> properties = 
      map.GetPropertyMaps()
         .Where(p => p.DestinationProperty
                      .Name
                      .Equals(destinationPropertyname, 
                              StringComparison.CurrentCultureIgnoreCase));
  PropertyMap sourceProperty = properties.First();
  IMemberGetter mg = sourceProperty.GetSourceValueResolvers()
                                   .Cast<IMemberGetter>()
                                   .First();

  return mg.MemberInfo;
}

但是,当我添加这样的自定义列映射时:

Mapper.CreateMap<Customer, CustomerViewModel>()
      .ForMember(dest => dest.Cell, opt => opt.MapFrom(src => src.CellPhone))
      .ForMember(dest => dest.Email, opt => opt.MapFrom(src => src.EmailAddress));

...无法从GetSourceResolvers()获取映射的源代码部分。

我感谢您的任何指导。

谢谢。

-Jessy Houle

1 个答案:

答案 0 :(得分:0)

这是否符合您的要求?

var map = Mapper.FindTypeMapFor<Customer, CustomerViewModel>();

foreach( var propertMap in map.GetPropertyMaps() )
{
    var dest = propertMap.DestinationProperty.MemberInfo;
    var source = propertMap.SourceMember;
}