Mapper does not contain definition for CreateMap C#

3.9k views Asked by At
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>);
}

Can you please help me to define properly this CreateMap and explain why this message is displayed after defining it this way? Why it cannot find this method?

1

There are 1 answers

1
Georg Patscheider On BEST ANSWER

As Ben has noted, using the static Mapper to create maps is deprecated in version 5. In any case, the code example you have show would have bad performance, because you would have reconfigured the maps on every request.

Instead, put the mapping configuration into a AutoMapper.Profile and initialize the mapper only once on application startup.

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