Skip to content

Mapping Graphs (DTO to DTO)

Leonardo Porro edited this page Jan 30, 2023 · 8 revisions

Replacing awesome products like AutoMapper or TinyMapper is not the goal of this library, however small plain class to class (i.e.: DTO to DTO) mapping can be done by accessing DbContext mapper or creating your own mapper instance.

Accessing DbContext mapper

dbContext.GetMapper().Map<SourceDTO, TargetDTO>(sourceDTO, targetDTO);

Profile key can be passed as a parameter to GetMapper method. All configurations applied to the mapper when UseMapping was called are also applied to this mapping operation.

Creating custom mapper

 MapperOptions mapperOptions = new MapperOptions();
 Mapper mapper = new Mapper(mapperOptions);

 TargetDTO result = mapper.Map<SourceDTO, TargetDTO>(new SourceDTO { Value = 2 });

 public class SourceDTO
 {
     public int Value { get; set; }
 }

 public class TargetDTO
 {
      public int Id { get; set; }

      public int Value { get; set; }
 }

No profile is supported but as many Mappers as needed can be created.

IMPORTANT!: Mappers instance contains a cache of a runtime compiled code and instances responsible to quickly perform mappings. Recreating this is very expensive so please handle mappers as singletons.