AutoMapper.Mapper does not contain definition for CreateMap

后端 未结 4 737
一生所求
一生所求 2020-12-07 11:02

This might be a basic question but wondering I am not getting AutoMapper.Mapper.CreateMap method.

Am I using wrong AutoMapper reference/package? Thanks

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-07 11:32

    Here is how I used AutoMapper in my code.

    Step 1 : Downloaded AutoMapper through nuget-packages.

    Version is

    
    

    Step 1 : Created DTO class

    public class NotificationDTO
    {
    
        public DateTime DateTime { get; private set; }
        public NotificationType Type { get; private set; }
        public DateTime? OriginalDateTime { get; private set; }
        public string OriginalVenue { get; private set; }
        public ConcertDTO Concert { get; set; }
    }
    
    public class ConcertDTO
    {
        public int Id { get; set; }
        public bool IsCancelled { get; private set; }
        public DateTime DateTime { get; set; }
        public string Venue { get; set; }
    
    }
    

    Step 2 : Created an AutoMapperProfile class which inherits from Profile

    using AutoMapper;
    using ConcertHub.DTOs;
    
    namespace ConcertHub.Models
    {
      public class AutoMapperProfile : Profile
      {
        public AutoMapperProfile()
        {
            CreateMap();
            CreateMap();
        }
      }
    }
    

    Step 3 : Registered AutoMapperProfile in the Application Start method of Global.asax file

    protected void Application_Start()
        {
            AutoMapper.Mapper.Initialize(cfg => cfg.AddProfile());
    
        }
    

    Finally the magic piece of code in the Api Controller

    public IEnumerable GetNewNotification()
        {
            var userId = User.Identity.GetUserId();
            var notifications = _dbContext.UserNotifications
                    .Where(un => un.UserId == userId && !un.IsRead)
                    .Select(un => un.Notification)
                    .Include(n => n.Concert)
                    .ProjectTo()//use Automapper.QueryableExtension namespace
                    .ToList();
    
            return notifications;
        }
    

    Hope it helps .

提交回复
热议问题