簡體   English   中英

映射器不包含CreateMap C#的定義

[英]Mapper does not contain definition for CreateMap C#

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,並解釋為什么以這種方式定義后會顯示此消息? 為什么找不到此方法

正如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配置

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM