c-sharp | dotnet-core

Using AutoMapper in a .NET Core Class Library

by Abhith RajanSeptember 11, 2019 · 2 min read · Last Updated:
Share this

AutoMapper is a handy helper library to do mapping between objects. In most scenarios, you might have an Entity Class and you want to map it to some DTO class or vice versa. With minimal configuration, AutoMapper can do this mapping without you creating a method where you map each field one by one.

Suppose I have to map Entity class to EntityDto and they look like,

1public class Entity
2{
3 public string Name {get;set;}
4 public Guid Id {get;set;}
5 public string CurrencyCode {get;set;}
6 public decimal CurrencyValue {get;set;}
7}
8
9public class EntityDto
10{
11 public string Name {get;set;}
12 public Guid Id {get;set;}
13 public Currency Currency {get;set;}
14}
15
16public class Currency
17{
18 public string Code {get;set;}
19 public string Value {get;set;}
20}
1using AutoMapper;
2...
3
4public class SomeService : ISomeService
5{
6 private IMapper _iMapper;
7
8 public SomeService()
9 {
10 // One time configuration
11 var config = new MapperConfiguration(cfg =>
12 {
13 cfg.CreateMap<Entity, EntityDto>().ForMember(dto => dto.Currency, map => map.MapFrom(source => new Currency
14 {
15 Code = source.CurrencyCode,
16 Value = source.CurrencyValue.ToString("0.00")
17 }));
18 });
19
20 _iMapper = config.CreateMapper();
21 }
22...
23}
24
25
26public async Task<DtoClass> GetAsync(Guid id)
27{
28 Entity entity = await GetEntityByIdAsync(id);
29
30 // using auto mapper to do the mapping
31 var dto = _iMapper.Map<DtoClass>(entity);
32
33 return dto;
34}

In the mapping configuration, we didn’t specify anything related Id, Name properties. AutoMapper will map them automatically since the source and destination property name matches for those.

Read more about the configuration and all on the official website of AutoMapper.

This page is open source. Noticed a typo? Or something unclear?
Improve this page on GitHub

Abhith Rajan

Written by Abhith Rajan Buy me a coffee
Abhith Rajan is an aspiring software engineer with more than 6 years of experience and proven successful track record of delivering technology-based products and services.

Related Videos