-
Notifications
You must be signed in to change notification settings - Fork 32
AutoMapper example
Martijn Bodeman edited this page Jul 7, 2025
·
7 revisions
Let's assume we have the following domain model and an associated DTO type. The only difference in this example between both types is that the BankAccountNumber property in the domain is encapsulated/represented by the Iban type:
namespace AutoMapperExample.Domain;
{
public record Payment(Iban BankAccountNumber, decimal Amount, string Currency);
}
namespace AutoMapperExample.Dtos;
{
public record PaymentDto(string BankAccountNumber, decimal Amount, string Currency);
}To map the Iban type to string and vice versa with AutoMapper, create a mapping profile class and inject IIbanParser. Then, create a two-way mapping between string and the Iban type.
public sealed class IbanMappingProfile : Profile
{
public IbanMappingProfile(IIbanParser ibanParser)
{
CreateMap<string, Iban>().ConvertUsing(s => ibanParser.Parse(s));
CreateMap<Iban, string>().ConvertUsing(s => s.ToString(IbanFormat.Electronic));
}
}Next, have another mapping profile in which you map between your domain model and DTO:
public sealed class MyProfile : Profile
{
CreateMap<Payment, PaymentDto>().ReverseMap();
}Make sure to register both mapping profiles with AutoMapper, and you're done!
See here for a similar working example.
