2017-07-25 71 views
0
public IEnumerable<NotificationDto> GetNewNotifications() 
{ 
    var userId = User.Identity.GetUserId(); 
    var notifications = _context.UserNotifications 
     .Where(un => un.UserId == userId) 
     .Select(un => un.Notification) 
     .Include(n => n.Gig.Artist) 
     .ToList(); 

    Mapper.CreateMap<ApplicationUser, UserDto>(); 
    Mapper.CreateMap<Gig, GigDto>(); 
    Mapper.CreateMap<Notification, NotificationDto>(); 

    return notifications.Select(Mapper.Map<Notification, NotificationDto>); 
} 

能否请你帮我确定正确此CreateMap,并解释为什么它定义这种方式后,显示此消息?为什么找不到这个方法映射器不包含定义CreateMap

+1

请参阅本又坏了同样的错误AutoMapper https://github.com/AutoMapper/AutoMapper/wiki/5.0-Upgrade-Guide – Ben

回答

1

正如本所指出的,使用静态映射器来创建地图在5版本已经过时。在任何情况下,代码示例,你有演出将有不好的表现,因为你会重新对每个请求的地图。

取而代之,将映射配置放入AutoMapper.Profile,并在应用程序启动时初始化映射器一次

using AutoMapper; 

// reuse configurations by putting them into a profile 
public class MyMappingProfile : Profile { 
    public MyMappingProfile() { 
     CreateMap<ApplicationUser, UserDto>(); 
     CreateMap<Gig, GigDto>(); 
     CreateMap<Notification, NotificationDto>(); 
    } 
} 

// initialize Mapper only once on application/service start! 
Mapper.Initialize(cfg => { 
    cfg.AddProfile<MyMappingProfile>(); 
}); 

AutoMapper Configuration

+0

的升级细节。 – Sarah

+1

不好意思啊,它应该是'CreateMap ();',而不是'Mapper.CreateMap ();'在配置文件中。我编辑了答案 –