1

Automapper v4.0 在方法中使用非常简单,有人可以帮助为 v5.0 重写它(特别是 Mapper 代码):

    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>);
    }

更新: 似乎 EF Core 没有投影 AutoMapper 映射的内容:

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

但是我确实使用以下代码在 Postman 中获得了结果:

        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
        });
4

1 回答 1

0

如果您想继续使用静态实例 - 唯一的变化是映射器初始化:

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

此外,您应该每个 AppDomain 只运行一次此代码(例如在启动时的某个地方),而不是每次调用GetNewNotifications.

于 2016-08-02T06:26:05.677 回答