Automapper-多次调用CreateMap [英] Automapper - CreateMap called multiple times

查看:162
本文介绍了Automapper-多次调用CreateMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What happens when I call Mapper.CreateMap with the same types multiple times?

它是否重写了以前的地图?如果是这样,如果我尝试创建已经创建的地图,是否有可能引发异常?

Does it rewrite the previous map? If so, is it possible to make it throw an exception if I try to create map, that is already created?

推荐答案

多次为同一组源和目标调用Mapper.CreateMap时,什么都不会发生,因为Mapper.CreateMap<TSource, TDestination>()并未为该文件设置任何扩展名映射配置. 如果您像这样设置IMappingExpression的替代 Mapper.CreateMap<TSource, TDestination>().ConstructUsing(x=>new TDestination(x.SomeField)), 是的,此映射的配置将替换为新的配置. 关于您问题的第二部分,我知道验证地图是否已创建的方法:

When calling Mapper.CreateMap for the same set of source and destination several times, nothing will happen at all as the Mapper.CreateMap<TSource, TDestination>() does not set up any extensions for a mapping configuration. If you set the overrides for IMappingExpression like this Mapper.CreateMap<TSource, TDestination>().ConstructUsing(x=>new TDestination(x.SomeField)), than yes, the configuration for this mapping will be replaced with the new one. Regarding the second part of your question, I know the way to verify if the map was already created:

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);
}

这篇关于Automapper-多次调用CreateMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆