Поиск  
Always will be ready notify the world about expectations as easy as possible: job change page
Apr 16, 2022

Enjoy using Mapster in .NET 6

Автор:
Mohsen Saniee
Источник:
Просмотров:
14639

Today, developers are paying more attention to mapping libraries than ever before, because modern architecture forces them to map object to object across layers. For example, in the past I prepared a repository for clean architecture in github. So it’s a template for visual studio, you can see it and get more information about modern architecture layers.

However, based on what I know most developers do the mapping by writing many lines of code, like this:

public IActionResult Post(ProductDto dto)
{
    Product product = new()
    {
        Name = dto.Name,
        Brand = dto.Brand,
        ...
        ...
        ...
        Size = dto.Size,
        Weight = dto.Weight,
        ...
        ...
        ColorId = dto.ColorId
    };
 
    ...
    return Ok();
}

I don’t know why some programmers choose this way for mapping! but I know, I don’t like this because it’s really boring and time consuming and I prefer use Mapping libraries such as AutoMapper and Mapster.
Since they are simple and fast. In addition to “Mapster” is fun and hashigh performance! you can see its repository in github.

So let’s get started!

1. Create a new ASP.NET Core Web API Project

2. Add Entity Models

Create a folder called “Entities” and Add Product.cs, Color.cs classes. It should be like below:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Brand { get; set; }
    
    public string WeightWithUnit { get; set; }
    public string Size { get; set; }


    public int ColorId { get; set; }
    public Color Color { get; set; }
}

public class Color
{
    public int Id { get; set; }
    public string Name { get; set; }

    public List<Product> Products { get; set; }
}

3. Install Mapster Nuget package

Add Mapster Nuget package:

PM> Install-Package Mapster

First see the basic usage:

Mapping to a new object:

var destObject = sourceObject.Adapt<Destination>();

Mapping to an existing object:

sourceObject.Adapt(destObject);

Queryable Extensions:

var destinations = context.Sources.ProjectToType<Destination>().ToList();

This was basic usage of Mapster, but in the following we show a different usage with customized configuration.

4. Add “BaseDto” Abstract class

Create a folder called “Dtos” and Add BaseDto.cs, ProductDto.cs classes. Actually our “Dto” classes implement the BaseDto class.

public abstract class BaseDto<TDto, TEntity> : IRegister
    where TDto : class, new()
    where TEntity : class, new()
{

    public TEntity ToEntity()
    {
        return this.Adapt<TEntity>();
    }

    public TEntity ToEntity(TEntity entity)
    {
        return (this as TDto).Adapt(entity);
    }

    public static TDto FromEntity(TEntity entity)
    {
        return entity.Adapt<TDto>();
    }

    private TypeAdapterConfig Config { get; set; }

    public virtual void AddCustomMappings() { }

    protected TypeAdapterSetter<TDto, TEntity> SetCustomMappings() => Config.ForType<TDto, TEntity>();

    protected TypeAdapterSetter<TEntity, TDto> SetCustomMappingsInverse() => Config.ForType<TEntity, TDto>();

    public void Register(TypeAdapterConfig config)
    {
        Config = config;
        AddCustomMappings();
    }
}
  • IRegister is an interface in Mapster library so it implemented to allow mappings to be found when scanning assemblies and place mappings is in the Register method.
  • Then we added some auxiliary methods for easier mapping:

    ToEntity()
    ToEntity(TEntity entity)
    FromEntity(TEntity entity)
  • Also we added three methods for customizing configuration of mappings:

    AddCustomMappings()
    SetCustomMappings()
    SetCustomMappingsInverse()

In the next steps, we will show how to use these methods…

5. Add ProductDto

Create the ProductDto class and implement the BaseDto class. Then override the AddCustomMappings() method and add customize mappings:

public class ProductDto : BaseDto<ProductDto,Product>
{
    public string Name { get; set; }
    public string Brand { get; set; }
    public string FullName { get; set; }

    public int Weight { get; set; }
    public string WeightUnit { get; set; }
    public string Size { get; set; }

    public int ColorId { get; set; }
    public string ColorName { get; set; }

    public override void AddCustomMappings()
    {
        SetCustomMappings()
            .Map(dest => dest.WeightWithUnit, src => src.Weight.ToString() + " " + src.WeightUnit);

        SetCustomMappingsInverse()
            .Map(dest => dest.FullName, src => $"{src.Name} ({src.Brand})")
            .Map(dest => dest.ColorName, src => src.Color.Name)
            .Map(dest => dest.Weight, src => Convert.ToInt32(src.WeightWithUnit.Split(" ",StringSplitOptions.None)[0]))
            .Map(dest => dest.WeightUnit, src => src.WeightWithUnit.Split(" ", StringSplitOptions.None)[1]);
    }
}

6. Add Mapster Configuration In Program Class

First, Create a folder called “Webframework” and add MapsterConfiguration.cs. So, add the assembly to scan classes that implemente IRegister.cs interface.

public static class MapsterConfiguration
{
    public static void AddMapster(this IServiceCollection services)
    {
        var typeAdapterConfig = TypeAdapterConfig.GlobalSettings;
        Assembly applicationAssembly = typeof(BaseDto<,>).Assembly;
        typeAdapterConfig.Scan(applicationAssembly);
    }
}

Then Call AddMapster() extensions method in program.cs class:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddMapster(); // <========<<

builder.Services.AddControllers();

...
...
...

7. Add api Controller and test mappings

Create a new api controller class by name “ProductsController” to test the mappings. Below are the implementation details:

[ApiController]
[Route("[controller]")]
public class ProductsController : ControllerBase
{
    private readonly ApplicationDbContext _context;

    public ProductsController(ApplicationDbContext context)
    {
        _context = context;
    }

    [HttpPost]
    public async Task<IActionResult> Post(ProductDto dto)
    {
        Product product = dto.ToEntity();

        _context.Add(product);

        await _context.SaveChangesAsync();

        return Ok(product);
    }

    [HttpGet]
    public async Task<IActionResult> Get(int productId)
    {
        ProductDto productDto = await _context
            .Products
            .Where(p => p.Id == productId)
            .ProjectToType<ProductDto>()
            .FirstOrDefaultAsync();

        return Ok(productDto);
    }

    [HttpGet]
    [Route("[controller]/[action]")]
    public async Task<IActionResult> GetAll()
    {
        var result = await _context
            .Products
            .ProjectToType<ProductDto>()
            .ToListAsync();

        return Ok(result);
    }
}

* It’s worth mentioning, also we added AppilcaitonDbContext.cs, EF core and Swagger in this project, So you can see the full source of this project in this github repository.

Eventually you can run this application and tests controller actions by Swagger and you see that everything is right.

8. Final point : how to create static method for mapping configuration

For example we add “HasFavoriteColor” propery to ProductDto.cs then add “GetMapsterConfig” static method:

public class ProductDto : BaseDto<ProductDto,Product>
{
    public string Name { get; set; }
    public string Brand { get; set; }
    public string FullName { get; set; }

    public int Weight { get; set; }
    public string WeightUnit { get; set; }
    public string Size { get; set; }

    public int ColorId { get; set; }
    public string ColorName { get; set; }

    public bool HasFavoriteColor { get; set; }

    public static TypeAdapterConfig GetMapsterConfig(int userFavoriteColorId)
    {
        return new TypeAdapterConfig()
            .NewConfig<Product, ProductDto>()
                .Map(dest => dest.FullName, src => $"{src.Name} ({src.Brand})")
                .Map(dest => dest.ColorName, src => src.Color.Name)
                .Map(dest => dest.HasFavoriteColor, src => src.ColorId == userFavoriteColorId) // <======<<
                .Config;
    }
    
    ...
    ...
}

Now we can use mapping in controller this way:

[HttpGet]
[Route("[controller]/[action]")]
public async Task<IActionResult> Products(int userFavoriteColorId)
{
    var result = await _context
        .Products
        .ProjectToType<ProductDto>(ProductDto.GetMapsterConfig(userFavoriteColorId)) //<======<<
        .ToListAsync();

    return Ok(result);
}

Summary

In this post, we saw one example of usage Mapster. It’s a very fun and simple and help keep your code structure clean.

You can get the source code from this git repository.

I hope you found this post helpful and easy to follow. Please let me know if you have any corrections and/or questions in the comments below.

Happy coding.

Похожее
Nov 19, 2020
We will demonstrate how to setup Elasticsearch and learn how to write basics statements. You will learn about the structure, commands, tools in Elasticsearch API and get it up and running using standard settings. Introduction We will be talking about...
Aug 11, 2021
Author: Mel Grubb
Code Generation Code generation is a great way to apply patterns consistently across a solution or to create multiple similar classes based on some outside input file, or even other classes in the same solution. The tooling has changed over...
месяц назад
Author: R M Shahidul Islam Shahed
In software development, writing clean, maintainable code is crucial for the long-term success of any project. However, even experienced developers can inadvertently introduce “code smells” — subtle indicators that something may be wrong with your code.   In C#, these...
Nov 30, 2023
Author: Dev·edium
Keeping your C# applications safe and sound. Keeping app secrets safe is always tricky for developers. We want to work on the main parts of the app without getting distracted by secret-keeping. But, the app’s safety is very important. So,...
Написать сообщение
Тип
Почта
Имя
*Сообщение
RSS
Если вам понравился этот сайт и вы хотите меня поддержать, вы можете
Soft skills: 18 самых важных навыков, которыми должен владеть каждый работник
Стили именования переменных и функций. Используйте их все
10 историй, как «валят» айтишников на технических интервью
Функции и хранимые процедуры в PostgreSQL: зачем нужны и как применять в реальных примерах
Семь итераций наивности или как я полтора года свою дебютную игру писал
Вопросы с собеседований, которые означают не то, что вы думаете
Путеводитель по репликации баз данных
5 приемов увеличения продуктивности разработчика
Топ 8 лучших ресурсов для практики программирования в 2018
Использование SQLite в .NET приложениях
LinkedIn: Sergey Drozdov
Boosty
Donate to support the project
GitHub account
GitHub profile