使用 Mapper.Initialize() 进行多个映射

Eln*_*naz 4 asp.net automapper

我在 ASP.Net 项目中使用AutoMapper V.6.1.1 作为映射器。之前我的配置如下:

 var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<A, B>();
            cfg.CreateMap<C, D>().ForMember(dest => dest.CityDesc, opt => opt.MapFrom(src => src.City));
        });
  var mapper = config.CreateMapper();
  var var1= mapper.Map<B>(request);
  var var2= mapper.Map<List<C>, List<D>>(result);
Run Code Online (Sandbox Code Playgroud)

现在,我想使用Mapper.Initialize(). 所以我用了:

 Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<A, B>();
            cfg.CreateMap<C, D>().ForMember(dest => dest.CityDesc, opt => opt.MapFrom(src => src.City));
        });
  var var1= Mapper.Map<B>(request);
  var var2= Mapper.Map<List<C>, List<D>>(result);
Run Code Online (Sandbox Code Playgroud)

我有一个运行时错误:

 Missing type map configuration or unsupported mapping. Mapping types:    A-> B
Run Code Online (Sandbox Code Playgroud)

使用多种配置有什么问题吗Mapper.Initialize?body中有一个映射的情况下不会出现错误Initialize()。我应该如何修复该错误?

RAM*_*RAM 6

Mapper.Initialize也许您的项目中有多个,而您的项目中不应该有多个Mapper.Initialize,否则它将被覆盖,并且您会丢失之前设置的映射配置Mapper.Initialize。现在可能会出现错误(Missing type map configuration or unsupported mapping.)


我建议您使用AutoMapper.Profile. 您可以以分组的形式(在单独的配置文件中)扭曲您的映射配置,然后立即注册所有主题Mapper.Initialize;)

看这个例子:

public class AB_Profile : Profile {
    protected override void Configure() {
        CreateMap<A, B>();
     // CreateMap<A, B1>();
     // CreateMap<A, B2>();
    }
}

public class CD_Profile : Profile {
    protected override void Configure() {
        CreateMap<C, D>()
        .ForMember(dest => dest.CityDesc, opt => opt.MapFrom(src => src.City));
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用上面的配置文件初始化映射器:

Mapper.Initialize(cfg => {
    cfg.AddProfile<AB_Profile >();
    cfg.AddProfile<CD_Profile >();
});
Run Code Online (Sandbox Code Playgroud)