Author : MD TAREQ HASSAN | Updated : 2020/08/01

What is AutoMapper?

Installation

Install-Package AutoMapper

Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection

Setup

Simple setup

var config = new MapperConfiguration(cfg => {

    cfg.CreateMap<FooEntity, FooDto>();
    
    // or
    
   cfg.CreateMap<FooEntity, FooDto>()
       .ForMember(dest => dest.FullName, opts => opts.MapFrom(src => $"{src.FirstName} {src.LastName}"));
    
    // ... ... ...
});

var mapper = config.CreateMapper(); // or IMapper mapper = new Mapper(config);

var fooDto = mapper.Map<FooDto>(fooEntity); // type is inferred: var dest = mapper.Map<FooEntity, FooDto>(...)
Simple setup with profile

FooProfile.cs

public class FooProfile : Profile
{
  public FooProfile()
  {
  
   CreateMap<FooEntity, FooDto>()
       .ForMember(dest => dest.FullName, opts => opts.MapFrom(src => $"{src.FirstName} {src.LastName}"));
       
    // ... ... ...
  }
}

Using FooProfile

var config = new MapperConfiguration(cfg => {
    cfg.AddProfile<FooProfile>();
});

var mapper = config.CreateMapper();

var fooDto = mapper.Map<FooDto>(fooEntity);

AutoMapper in aspnet core with Dependency Injection

AddAutoMapper() in Startup.cs

services.AddAutoMapper(typeof(Startup));

// ... ... ...

If models are in different package

services.AddAutoMapper(typeof(a_profile_classe_in_other_assembly).GetTypeInfo().Assembly);

See: https://github.com/AutoMapper/AutoMapper/issues/2300#issuecomment-342157947

Get IMapper by DI

FooService.cs

public class FooService {

  private readonly IMapper _mapper;
  
  private readonly IFooRepo _repo;
  
  public UserController(IMapper mapper, IFooRepo repo) {
    _mapper = mapper;
    _repo = repo;
  }

  public FooDto GetFoo(long id){
  
    FooEntity fooEntity = _repo.GetFoo(id);
    
    FooDto fooDto = _mapper.Map<FooDto>();
    
    return fooDto 
  }
  
  // ... ... ...
}

Mappings

Ignore property

// UpdateEmployeeDto => Employee
CreateMap<UpdateEmployeeDto, Employee>().ForMember(dest => dest.Id, opts => opts.Ignore());

Ignore null values

// Just for compying values
CreateMap<Employee, Employee>().ForMember(dest => dest.Id, opts => opts.Ignore())
    .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));

See: