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 并解释为什么在以这种方式定义后会显示此消息?为什么找不到这个方法?
答案 0 :(得分:2)
正如Ben所指出的那样,在版本5中不推荐使用静态Mapper来创建映射。无论如何,您显示的代码示例会有不良的性能,因为您可能会在每个请求上重新配置映射。
相反,将映射配置放入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>();
});