Automapper:第二个映射抛出缺少的typemap

时间:2017-09-21 10:55:28

标签: c# automapper

初始化Automapper并调用Mapper.Map后,typeMap为null,第二次调用Mapper.Map会抛出异常“Missing type map”。

我已经初始化了Mapping:

AutoMapper.Mapper.Initialize(cfg =>
                { 
                    cfg.CreateMap<Role, AppRole>();
                });
                Mapper.AssertConfigurationIsValid();

然后打电话:

var roleTest = Mapper.Map<Role, AppRole>(role);
var mapped = Mapper.Configuration.FindTypeMapFor(typeof(Role), typeof(AppRole)); // here mapped is null
var roleTestSecond = Mapper.Map<Role, AppRole>(role); // exception thrown "Missing type map"

您是否知道为什么第二个映射不起作用且缺少类型映射?我错过了什么吗?

2 个答案:

答案 0 :(得分:1)

静态Mapper遇到了同样的问题。我的解决方案是创建像ConveriosnExtensions这样的静态类。见下文:

      public static class DataConversionsExtensions
    {
        private static readonly IMapper Mapper;

        static DataConversionsExtensions()
        {
            var configuration = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Field, DbField>();
                cfg.CreateMap<DbField, Field>();  });

            Mapper = new Mapper(configuration);
        }

        public static Field ToField(this DbField field)
        {
            return Mapper.Map<Field>(field);
        }

        public static DbField ToDbField(this Field field)
        {
            return Mapper.Map<DbField>(field);
        }
}

通过这种方式,您可以确定当前使用的配置,并且可以非常轻松地使用转换:

var field = dbfield.ToField();

这也很好地封装了整个过程,因此不再需要复制代码粘贴

答案 1 :(得分:0)

根据我的理解,您需要密封配置,以便FindTypeMapFor返回任何内容。

尝试添加一个密封调用来自动映射器初始化。

AutoMapper.Mapper.Initialize(cfg =>
            { 
                cfg.CreateMap<Role, AppRole>();
            });
            Mapper.Configuration.Seal();
            Mapper.AssertConfigurationIsValid();
相关问题