将 Automapper v5.0 的代码重写为 v4.0

Rewrite code for Automapper v5.0 to v4.0

A​​utomapper 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
        });

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

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

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