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 .
- Automapper (395M Downloads as per article published date)
- 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
-
Performance wise it is better than Automapper (Memory and Time)
-
Easy to use because we are mostly playing with adapt method.
-
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)
We have two ways to achieve this
- Use .Adapt method directly in desired class
- Create a static class that contains all Mappings (I am using this)
While working with database you can use Mapster via Queryable as well , it has ProjectToType method
You can add your custom mappings as well by creating an extension method of IServiceCollection and then by adding its configuration in Program.cs
Key Points
Here are some other points about Mapster :
- If you want to ignore some properties then use .Ignore while mapping.
- For two ways mappings use .TwoWays
- For further details check here at official Github Repo of Mapster
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place