AutoMapper is a simple library built to getting rid of code that mapped one object to another. explore more about Auto-mapper here.

Add it from NuGet packages manager or execute below command

PM> Install-Package AutoMapper

here is sample code to use it…

  1. Create a class named AutoMapperConfig, which will define what is getting mapped with whom… sample is below ..
using AutoMapper;
using SoftSchool.Model;
using SoftSchoolVM;
using System;

namespace SoftSchool.AutoMapper
    public static class AutoMapperConfig
        /// <summary>
        /// only for mapping model and View Model purpose 
        /// </summary>
        /// <returns></returns>
        public static MapperConfiguration CreateMapperConfig()

                var config = new MapperConfiguration(cfg =>

                    cfg.CreateMap<City, CityVM>()
                        .ForMember(dest => dest.Addresses, opt => opt.Ignore())
                        .ForMember(dest => dest.Suburbs, opt => opt.Ignore());

                    cfg.CreateMap<ClassSubject, ClassSubjectVM>();
                    cfg.CreateMap<Nation, NationVM>()
                        .ForMember(dest => dest.Addresses, opt => opt.Ignore())
                        .ForMember(dest => dest.States, opt => opt.Ignore()); //.ReverseMap(); //

                    cfg.CreateMap<Optionset, OptionsetVM>();

                    cfg.CreateMap<Person, PersonVM>()
                        .ForMember(dest => dest.Addresses, opt => opt.Ignore())
                        .ForMember(dest => dest.Classes, opt => opt.Ignore());

                    cfg.CreateMap<State, StateVM>()
                        .ForMember(dest => dest.Addresses, opt => opt.Ignore())
                        .ForMember(dest => dest.Cities, opt => opt.Ignore());

                    cfg.CreateMap<Subject, SubjectVM>()
                     .ForMember(dest => dest.ClassSubjects , opt => opt.Ignore());

                    cfg.CreateMap<Suburb, SuburbVM>()
                        .ForMember(dest => dest.Addresses, opt => opt.Ignore());

                return config;
            catch (Exception e)
                throw new Exception(e.Message, e);


2. and in your repository just create a global declaration like

private readonly IMapper _mapper = AutoMapperConfig.CreateMapperConfig().CreateMapper()3. 

3. it will be used like ..

public List<NationVM> GetAllNations()
           return _mapper.Map<List<Nation>, List<NationVM>>(GetNationsQuery().ToList());

You can explore more on same topic here ..

Thanks !!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s