2016-08-02 62 views
1

Automapper V4.0是非常直截了当的方法中使用,有人可以帮这个改写为V5.0,请(特别是映射代码):重写代码

public IEnumerable<NotificationDto> GetNewNotifications() 
    { 
     var userId = User.Identity.GetUserId(); 
     var notifications = _context.UserNotifications 
      .Where(un => un.UserId == userId && !un.IsRead) 
      .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>); 
    } 

UPDATE: 看来,EF Core不什么项目AutoMapper是映射:

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

但我得到的邮差用下面的代码的结果:

 return notifications.Select(n => new NotificationDto() 
     { 
      DateTime = n.DateTime, 
      Gig = new GigDto() 
      { 
       Artist = new UserDto() 
       { 
        Id = n.Gig.Artist.Id, 
        Name = n.Gig.Artist.Name 

       }, 
       DateTime = n.Gig.DateTime, 
       Id = n.Gig.Id, 
       IsCancelled = n.Gig.IsCancelled, 
       Venue = n.Gig.Venue 
      }, 
      OriginalVenue = n.OriginalVenue, 
      OriginalDateTime = n.OriginalDateTime, 
      Type = n.Type 
     }); 

回答

0

如果你想使用静态实例保持 - 唯一的变化是在映射器初始化:

Mapper.Initialize(cfg => 
{ 
    cfg.CreateMap<ApplicationUser, UserDto>(); 
    cfg.CreateMap<Gig, GigDto>(); 
    cfg.CreateMap<Notification, NotificationDto>(); 
}); 

你也应该(在启动例如某处)每个AppDomain只有一次运行这个代码,而不是每次都您致电GetNewNotifications

+0

mapper.map行似乎不起作用。看起来也需要重写 – Reza

+0

你有什么错误吗?对我工作正常 –

+0

Intellisense正在抱怨此行返回notifications.Select(Mapper.Map ); – Reza