Featured
Mapster
Last modified: June 03, 2022Do not waste your time on Mapping class/object, let Mapster do it. Mapster boasts of superior performance compared to AutoMapper.
1. Create a .NET 6 application e.g. MVC or Razor Page
2. Install packages
- Open Package Manager Console
- excute the following commands
- dotnet new tool-manifest
- dotnet tool install Mapster.Tool
- Install-Package Mapster.Core
- Install-Package Mapster
3. Entities
- Create a folder called Entities
- Create Project Class and save it Entities
public class Product
{
public int Id { get; set; }
public string Sku { get; set; }
public string Name { get; set; }
}
- Create Person Class and save it Entities.
- Please note it has private information which should not expose to all user in the system.
- Mapster make it easier to exclude certian fields in the class.
- iIf field has DataMember attribute, it will generate, and else it ignore it.
public class Person
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
public int Age { get; set; }
public double Salary { get; set; }
public string BankAccount { get; set; }
}
4. Edit project csproj.
- add following code to your csproj file.
<Target Name="Mapster" AfterTargets="AfterBuild">
<Exec WorkingDirectory="$(ProjectDir)" Command="dotnet tool restore" />
<Exec WorkingDirectory="$(ProjectDir)" Command="dotnet mapster model -a "$(TargetDir)$(ProjectName).dll"" />
<Exec WorkingDirectory="$(ProjectDir)" Command="dotnet mapster extension -a "$(TargetDir)$(ProjectName).dll"" />
<Exec WorkingDirectory="$(ProjectDir)" Command="dotnet mapster mapper -a "$(TargetDir)$(ProjectName).dll"" />
</Target>
<ItemGroup>
<Generated Include="**\*.g.cs" />
</ItemGroup>
<Target Name="CleanGenerated">
<Delete Files="@(Generated)" />
</Target>
5. Auto Generate DTO files
- Build the project
- You can see following two DTOs generated
ProductDto
public partial class ProductDto
{
public int Id { get; set; }
public string Sku { get; set; }
public string Name { get; set; }
}
PersonDto
public partial class PersonDto
{
public int Id { get; set; }
public string Name { get; set; }
}
6. Mapping
- Map between two classes
var productDto = new ProductDto
{
Id = 2,
Name = "a",
};
var destObject = productDto.Adapt<Product>();
- Map between two list/array
var products = new List<Product>()
{
new Product{Sku = "1", Id = 1, Name="iphone11"},
new Product{Sku = "2", Id = 2, Name = "iphone12"}
};
var destinations = products.Adapt<List<ProductDto>>();