Skip to content

AutoMapper C#

When it comes to different layers of a solution communicating there are always DTOs (Data Transfer Objects)
going back and forth and inevitably there is a lot of mapping. If there are external libraries or even
3rd party services then mapping an external object to the one our application already uses becomes
tedious and error prone task. (Dont’t even get me started with SPA’s Angular JWT and all that jazz.)
Thankfully for those of who develop in C# there is AutoMapper.

AutoMapper

As i noticed from my NuGet package manager, AutoMapper has been downloaded more than 22 million times!
That alone says a lot about how useful is this library.

Let’s start with a simple example where we want to map a PersonDto to a CustomerDto

public class PersonDto
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}
public class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

First we have to go to the starting point of our application like the Startup.cs for .NETCore and initialize our Mapper.

Mapper.Initialize(cfg => cfg.CreateMap<PersonDto, Customer>());

Then we can use the mapper like this

Customer customer = Mapper.Map<Customer>(personDto);

AutoMapper has a naming convention that is, it will map automatically from source object to destination object
all the properties with exactly the same name. So the properties FirstName, LastName, ContactMail, Age will all be mapped
successfully. However, I want PersonDto to carry an additional property called SubscriptionDate of type string.
On the other side my Customer object will have a new DateTime property called SubscriptionDate. Now we have
two problems that must be addressed. First our properties have different names and second different types.

For the first problem we will chain the method ForMember

cfg.CreateMap<PersonDto, Customer>()
 .ForMember(dest => dest.SubscriptionEndDate, opt => opt.MapFrom(src => src.SubscriptionDate));

For the second problem we must provide another mapping between string and Datetime types.

Mapper.Initialize(cfg =>
{
 cfg.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter());
 cfg.CreateMap<PersonDto, Customer>()
  .ForMember(dest => dest.SubscriptionEndDate, opt => opt.MapFrom(src => src.SubscriptionDate));
});

Summary

And that’s all there (basically) is to it! Automapper is a powerfull yet simple tool and is something definitely worth checking.
If you would like to take a look at the source code you can find it at GitHub (Project c-sharp-features).

You can always Buy me a coffeeBuy me a coffee and help me stay awake to continue my excavations!

0

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *