Mapster in .NET Core for Mappings

Why we need Mappers

While working with .NET we often need to convert the different objects (Database objects to DTO’s/Models or vice versa). That’s where mappers come in action.

In the world of mapping we have multiple libraries but these two has got big following and usage .

  1. Automapper (395M Downloads as per article published date)
  2. Mapster (12M Downloads as per article published date)

I have already covered the Automapper in a different post you can check here , let’s see how to use Mapster in this episode.

Some Benefits

Before moving forward here are the benefits of Mapster

  1. Performance wise it is better than Automapper (Memory and Time)

  2. Easy to use because we are mostly playing with adapt method.

  3. Comes with variety of mapping scenarios.

Installation

Install Mapster with the NuGet CLI

Install-Package Mapster

How to use

It is quite simple to use Mapster using adapt method of library , suppose we have DTO(or Model whatever you name it) and Entity (Supposed to be a database class)

Mapster in .NET Core for Mappings

We have two ways to achieve this

  1. Use .Adapt method directly in desired class
  2. Create a static class that contains all Mappings (I am using this)

Mapster in .NET Core for Mappings

While working with database you can use Mapster via Queryable as well , it has ProjectToType method

Mapster in .NET Core for Mappings

You can add your custom mappings as well by creating an extension method of IServiceCollection and then by adding its configuration in Program.cs

Mapster in .NET Core for Mappings

Key Points

Here are some other points about Mapster :

  1. If you want to ignore some properties then use .Ignore while mapping.
  2. For two ways mappings use .TwoWays
  3. For further details check here at official Github Repo of Mapster

This article was originally published at https://mwaseemzakir.substack.com/ on .

Whenever you're ready, there are 3 ways I can help you:

  1. Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
  2. Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
  3. Patreon community : Get access to all of my blogs and articles at one place