Friday, April 12, 2019

Using AutoMapper - Map from one object to another object C#

1) Install the automapper to your project through NuGet package manager


2) Initialize the automapper in the Global.asax file

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


3) My classes to be mapped are:

   //DAO classes
    public class Passenger
    {
        public int OrderNo { get; set; }
        [Key]
        public int TcNo { get; set; }
        public string PsgrName { get; set; }
        public string FlightId { get; set; }
        public string CarrierCode { get; set; }
        public string FlightNo { get; set; }
        public string Origin { get; set; }
        public string Destination { get; set; }
        public string DepDateTime { get; set; }
        public string ArrDateTime { get; set; }
        public virtual ICollection<Device> Devices { get; set; }
    }

    public class Device
    {
        public string Language { get; set; }
        [Key]
        public string RegistrationId { get; set; }
        public string DeviceType { get; set; }
        public int TcNo { get; set; }
    }

//DTO classes to be mapped
    public class PassengerDTO
    {
        public int OrderNo { get; set; }
        public int TcNo { get; set; }
        public string PsgrName { get; set; }
        public string FlightId { get; set; }
        public string CarrierCode { get; set; }
        public string FlightNo { get; set; }
        public string Origin { get; set; }
        public string Destination { get; set; }
        public string DepDateTime { get; set; }
        public string ArrDateTime { get; set; }
        public virtual ICollection<DeviceDTO> Devices { get; set; }
    }

    public class DeviceDTO
    {
        public string Language { get; set; }
        public string RegistrationId { get; set; }
        public string DeviceType { get; set; }
    }

4) Create a mapper profile to map between the DAO and DTO object

    public class AutoMapperProfile : Profile
    {
        public AutoMapperProfile()
        {
            CreateMap<Passenger, PassengerDTO>();
            CreateMap<Device, DeviceDTO>();
        }
    }

5) Do the actual mapping in the code

IList<PassengerDTO> data = db.Passengers.Where(p => p.FlightId == FlightId).ProjectTo<PassengerDTO>().ToList();