Mapper不包含CreateMap C#的定义

问题描述 投票:0回答:1
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并解释为什么这个消息在这样定义之后会显示出来吗?为什么找不到这种方法?

javascript c# linq mapper automapper-3
1个回答
3
投票

正如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>();
});

AutoMapper Configuration

© www.soinside.com 2019 - 2024. All rights reserved.