对象映射Mapster使用 #

使用 `Mapster` 以外的拓展说明

Mall3s 框架提供了 Mapster 的拓展 Mall3s.Extras.ObjectMapper.Mapster,如需使用第三方如 AutoMapper 则无需安装此拓展。

对象映射 #

简单来说,就是将一个对象的数据根据特定规则批量映射到另一个对象中,减少手工操作和降低人为出错率。如将 DTO 对象映射到 Entity 实体中,反之亦然。

先看例子 #

在过去,我们需要将一个对象的值转换到另一个对象中,我们需要这样做,如:

var entity = repository.Find(1);

var dto = new Dto();
dto.Id = entity.Id;
dto.Name = entity.Name;
dto.Age = entity.Age;
dto.Address = entity.Address;
dto.FullName = entity.FirstName + entity.LastName;
dto.IdCard = entity.IdCard.Replace("1234", "****");

上面的例子似乎没有任何问题,但是如果很多地方需要这样的赋值操作、或者相同的赋值操作在多个地方使用,又或者一个类中含有非常多的属性或自定义赋值操作。那么这样的操作效率极低,容易出错,且代码非常臃肿和冗余。

所以,实现自动映射赋值和支持特殊配置的需求就有了。目前 C# 平台有两个优秀的对象映射工具:MapsterAutoMapperMall3s 框架中,推荐使用 Mapster (opens new window)Mapster (opens new window) 是一款极易使用且超高性能的对象映射框架。

Mapster 使用 #

现在,我们可以通过 Mapster 提供的对象映射方法:Adapt 方法改造上面的例子:

安装拓展包

Mall3s.Core 层安装 Mall3s.Extras.ObjectMapper.Mapster 拓展包,无需手动调用,Mall3s 会自动加载并调用。

快速入门 #

var entity = repository.Find(1);
var dto = entity.Adapt<Dto>();

仅仅一行代码就可以实现 entity -> dto 的转换,如果涉及到赋值的复制操作,如 dto.FullNamedto.IdCard,我们只需要自定义映射规则类即可。

自定义映射规则 #

using Mapster;
using System;

namespace Mall3s.Application
{
    public class Mapper : IRegister
    {
        public void Register(TypeAdapterConfig config)
        {
            config.ForType<Entity, Dto>()
                .Map(dest => dest.FullName, src => src.FirstName + src.LastName)
                .Map(dest => dest.IdCard, src => src.IdCard.Replace("1234", "****"));
        }
    }
}

小知识

该映射文件 Mapper.cs 可以放在任何项目或文件夹中,Mall3s 会在程序启动的时候自动扫描并注入配置。

依赖注入方式 #

Mapster 除了提供 Adapt 拓展方法以外,同时还提供依赖注入的方式。

public  Person(IMapper mapper)
{
  var dto =  _mapper.Map<Dto>(entity);
}

EFCore 配合 #

Mapster 还提供了 ProjectToType Linq 拓展方法减少我们手动 Select 操作,如:

正常的操作:

var destinations = context.Sources
        .Select(p => new Destination {
            Id = p.Id,
            Name = p.Name,
            Surname = p.Surname,
            ....
        })
        .ToList();

使用 Mapster 之后:

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

全局默认配置 #

Mall3s 提供全局默认映射配置选项 TypeAdapterConfig.GlobalSettings.Default,可在 Startup 中配置即可,如:

TypeAdapterConfig.GlobalSettings.Default
    .PreserveReference(true);

了解更多

想了解更多 Mapster 知识可查阅 Mapster - Wiki (opens new window) 文档。

上次更新: 3/10/2023, 5:09:25 PM