-
Notifications
You must be signed in to change notification settings - Fork 33
AutoMapper example
Martijn Bodeman edited this page Aug 24, 2023
·
4 revisions
Assuming you have the following domain and a DTO 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.