Thursday, November 5, 2015

Mapping using automapper

Need  for using Automapper 

Eventually, in any application, a developer will need to translate data from one object type to another.
Common examples include DTOs (Data Transfer Objects), View Models, or even just some request or response object from a service or Web API call.

Usually we end up doing manual mapping.

  •          We need to do it in every page or repository where we are using it
  •          Difficult to maintain code
  •          We end up exposing actual properties from the database to the outside world

  •          Lines of code has been reduced
  •          Easy for maintainance
  •          Mapping is loaded at application start up
  •          We are exposing the member what we have defined in view model

Typical data flow

Using Automapper

Steps to use Auto Mapper
  • Download Automapper using package manager


  • Create a config file 

public class MapperConfig
        public static void CreateMaps()
            Mapper.CreateMap<SearchResult, OrgViewModel>()
                .ForMember(dest => dest.FirstName, opt => opt.MapFrom(src => src.first_name))
                .ForMember(dest => dest.LastName, opt => opt.MapFrom(src => src.last_name))

  • In global.asax.cs call Mapper.config  
      protected void Application_Start()
  • Now we can use the mapping anywhere in our solution

       Mapper.Map<IEnumerable<SearchResult>, IEnumerableOrgViewModel>> ((searchList).ToList(), model);

No comments:

Post a Comment