Skip to main content

User implemented mapping methods

If Mapperly cannot generate a mapping, one can implement it manually simply by providing a method body in the mapper declaration:

[Mapper]
public partial class CarMapper
{
public partial CarDto CarToCarDto(Car car);

private int TimeSpanToHours(TimeSpan t) => t.Hours;
}

Whenever Mapperly needs a mapping from TimeSpan to int inside the CarMapper implementation, it will use the provided implementation.

Use external mappings

Mapperly can also consider mappings implemented in other classes. In order for Mapperly to find the mappings, they must be made known with UseMapper / UseStaticMapper.

For static mappings, UseStaticMapper can be used:

[Mapper]
[UseStaticMapper<BananaMapper>] // for c# language level ≥ 11
[UseStaticMapper(typeof(BananaMapper))] // for c# language level < 11
public static partial class BoxMapper
{
public static partial BananaBox MapBananaBox(BananaBoxDto dto);
}

public static class BananaMapper
{
public static Banana MapBanana(BananaDto dto)
=> new Banana(dto.Weigth);
}

Whenever Mapperly needs a mapping from BananaBox to BananaBoxDto inside the BoxMapper implementation, it will use the provided implementation by the BananaMapper.

Used mappers themselves can be Mapperly backed classes.