Automapper - 多次调用CreateMap

时间:2011-06-15 09:04:40

标签: automapper

当我多次调用具有相同类型的Mapper.CreateMap时会发生什么?

是否重写了之前的地图?如果是这样,如果我尝试创建已经创建的地图,是否可以使它抛出异常?

1 个答案:

答案 0 :(得分:23)

多次为同一组源和目标调用Mapper.CreateMap时,由于Mapper.CreateMap<TSource, TDestination>()没有为映射配置设置任何扩展,因此根本不会发生任何事情。 如果你像这样设置IMappingExpression的覆盖 Mapper.CreateMap<TSource, TDestination>().ConstructUsing(x=>new TDestination(x.SomeField)), 是的,此映射的配置将替换为新映射。 关于问题的第二部分,我知道验证地图是否已经创建的方法:

public TDestination Resolve<TSource, TDestination>(TSource source)
{
     var mapped = Mapper.FindTypeMapFor(typeof(TSource), typeof(TDestination)); //this will give you a reference to existing mapping if it was created or NULL if not

     if (mapped == null)
     {
        var expression = Mapper.CreateMap<TSource, TDestination>();
     }
     return Mapper.Map<TSource, TDestination>(source);
}
相关问题