Automapper 5.0.2 - 缺少类型映射配置或不支持的映射

时间:2016-07-26 19:35:40

标签: automapper

我已经在网上找到了关于这个问题的所有内容,但没有任何帮助。这是我的代码:

 Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<User, UserListViewModel>()
            .ForMember("RoleNames", c => c.Ignore())
            .ForMember("CostCentreNames", c => c.Ignore())
            .ForMember("RollupGroupNames", c => c.Ignore())
            .ForMember(c => c.CostCentres, m => m.MapFrom(d => d.DetailCostCentres))
            ;
        });

        Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<CostCentre, CostCentreListViewModel>();

        });

var users = _repo.AllIncluding(u => u.Roles, u=>u.CostCentres).OrderBy(u => u.UserName).ToList();
var  model = Mapper.Map<List<User>, List<UserListViewModel>>(users);

Mapper.Map给了我错误:

  

缺少类型映射配置或不支持的映射。

     

映射类型:
      用户 - &gt; UserListViewModel
      Model.Models.User - &gt; Model.ViewModels.UserListViewModel
        描述:执行当前Web请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

     

异常详细信息:AutoMapper.AutoMapperMappingException:缺少类型映射配置或不支持的映射。

     

映射类型:
  用户 - &gt; UserListViewModel
  Model.Models.User - &gt; Model.ViewModels.UserListViewModel

     

来源错误:

     

第45行:
     第46行:var users = _repo.AllIncluding(u =&gt; u.Roles,u =&gt; u.CostCentres).OrderBy(u =&gt; u.UserName)。ToList();
     第47行:var model = Mapper.Map,List&gt;(用户);
     第48行:返回模型;
    第49行:}

2 个答案:

答案 0 :(得分:5)

您只能进行一次Mapper.Initialize来电:

 Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<User, UserListViewModel>()
            .ForMember("RoleNames", c => c.Ignore())
            .ForMember("CostCentreNames", c => c.Ignore())
            .ForMember("RollupGroupNames", c => c.Ignore())
            .ForMember(c => c.CostCentres, m => m.MapFrom(d => d.DetailCostCentres));
            cfg.CreateMap<CostCentre, CostCentreListViewModel>();
        });

答案 1 :(得分:0)

感谢您的回复。我实际上认为那个,但它没有解决我的问题。我将Automapper v 2升级到v5,它需要一些代码修改才能工作。就我而言,它无法自动处理对象内的集合。我必须添加一行代码来指定:

Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<User, UserListViewModel>()
            .ForMember("RoleNames", c => c.Ignore())
            .ForMember("CostCentreNames", c => c.Ignore())
            .ForMember("RollupGroupNames", c => c.Ignore())
            .ForMember(c => c.CostCentres, m => m.MapFrom(d => d.DetailCostCentres));
            cfg.CreateMap(typeof(Role), typeof(RoleViewModel));
            cfg.CreateMap(typeof(CostCentre), typeof(CostCentreListViewModel));
        });