Skip to content
chaowlert edited this page Aug 1, 2020 · 20 revisions

Mapster.Tool

Here are steps to add code generation.

  1. Define interface to generate code. Your interface must annotate with [Mapper] in order for tool to pickup for generation.

This is example interface.

[Mapper]
public interface IProductMapper
{
    ProductDTO Map(Product customer);
}

You can add multiple members as you want. All member names are flexible.

[Mapper]
public interface ICustomerMapper
{
    //for queryable
    Expression<Func<Customer, CustomerDTO>> ProjectToDto { get; }
    
    //map from POCO to DTO
    CustomerDTO MapToDto(Customer customer);

    //map back from DTO to POCO
    Customer MapToPoco(CustomerDTO dto);

    //map to existing object
    Customer MapToExisting(CustomerDTO dto, Customer customer);
}

At this point, you can use your interface in your code.

var dtos = context.Customers.Select(mapper.ProjectToDto);
var dto = mapper.MapToDto(poco);
mapper.MapToExisting(dto, poco);
  1. Install Mapster.Tool

You can install per repo

#skip this step if you already have dotnet-tools.json
dotnet new tool-manifest 

dotnet tool install Mapster.Tool

Or you can install globally on your machine

dotnet tool install -g Mapster.Tool

NOTE: the tool required .NET Core 2.1 or .NET Core 3.1 on your machine.

  1. Add setting to you csproj
<Target Name="mapster" AfterTargets="AfterBuild">
    <Exec WorkingDirectory="$(ProjectDir)" Command="dotnet mapster -a $(TargetDir)$(ProjectName).dll" />
</Target>

That's it, now Mapster will automatically generate codes after build.

Clone this wiki locally