一、Mapster简介

发布时间 2023-12-14 14:56:18作者: 漫思

一、Mapster简介

1、什么是Mapster(官方文档地址:https://github.com/MapsterMapper/Mapster)

  Mapster是一个高性能的用于对象映射的类库,同类型的产品还有AutoMapper。它提供了一系列的API和工具,以下为几个重要的类和接口:

  • @Adapt注解:用于将实体类映射到数据库表中的指定列上。
  • @Mapper注解:用于将实体类映射到数据库表中的指定列上。
  • Entity接口:定义了实体类的属性和映射规则。
  • Mapper接口:定义了映射规则的具体实现。
  • Query接口:定义了查询语句的规则。
  • DataStore接口:定义了数据存储的接口。

2、Mapster与AutoMapper的性能对比:

方法平均值标准偏差错误第0代第1代第2代分配
“Mapster 6.0.0” 108.59毫秒 1.198毫秒 1.811毫秒 31000 - - 124.36 MB
“Mapster 6.0.0(罗斯林)” 38.45毫秒 0.494毫秒 0.830毫秒 31142.8571 - - 124.36 MB
'Mapster 6.0.0(FEC)' 37.03毫秒 0.281毫秒 0.472毫秒 29642.8571 - - 118.26 MB
'Mapster 6.0.0(Codegen)' 34.16毫秒 0.209毫秒 0.316毫秒 31133.3333 - - 124.36 MB
“ExpressMapper 1.9.1” 205.78毫秒 5.357毫秒 8.098毫秒 59000 - - 236.51 MB
“AutoMapper 10.0.0” 420.97毫秒 23.266毫秒 35.174毫秒 87000 - - 350.95 MB

二、Mapster帮助类

 
/**
*┌──────────────────────────────────────────────────────────────┐
*│ 描    述:Mapster映射帮助类-基础使用 (Mapster 版本7.3.0或7.2.0)                                              
*│ 作    者:执笔小白                                              
*│ 版    本:1.0                                       
*│ 创建时间:2023-06-28 15:01:11                            
*└──────────────────────────────────────────────────────────────┘
*┌──────────────────────────────────────────────────────────────┐
*│ 命名空间: Util.ObjMapperUtil                               
*│ 类    名:MapsterHelper                                    
*└──────────────────────────────────────────────────────────────┘
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Mapster;
using MapsterMapper;

namespace fly_webapi.Util.ObjMapperUtil
{
    /// <summary>
    /// Mapster映射帮助类 -基础使用
    /// Mapster 版本7.3.0(或7.2.0)
    /// ASP.NET使用时可直接services.AddMapster();
    /// </summary>
    public class MapsterHelper
    {
        #region 实体映射
        /// <summary>
        /// 1.1、类型映射_默认字段一一对应
        /// T需要映射后的实体 = 需要映射的实体.Adapt<T需要映射后的实体>();
        /// </summary>
        /// <typeparam name="TSource">源类型</typeparam>
        /// <typeparam name="TDestination">目标类型</typeparam>
        /// <param name="tSource">源数据</param>
        /// <returns></returns>
        public static TDestination MapsterTo<TSource, TDestination>(TSource tSource) where TSource : class where TDestination : class
        {
            if (tSource == null) return default;

            return tSource.Adapt<TDestination>();
        }
        /// <summary>
        /// 1.2、类型映射_默认字段一一对应 (映射到现有对象)
        /// T需要映射后的实体 = 需要映射的实体.Adapt<T需要映射后的实体>();
        /// </summary>
        /// <typeparam name="TSource">源类型</typeparam>
        /// <typeparam name="TDestination">目标类型</typeparam>
        /// <param name="tDestination">目标对象</param>
        /// <param name="tSource">源数据</param>
        /// <returns></returns>
        public static TDestination MapsterTo<TSource, TDestination>( TDestination tDestination, TSource tSource) where TSource : class where TDestination : class
        {
            if (tSource == null) return default;

            return tSource.Adapt(tDestination);
        }

        /// <summary>
        /// 2、类型映射
        /// ① 字段名称不对应
        /// ② 类型转化
        /// ③ 字段省略
        /// ④ 字段名称或类型不对应
        /// ⑤ 条件赋值或null处理
        /// ⑥ 组合赋值
        /// </summary>
        /// <typeparam name="TSource">源类型</typeparam>
        /// <typeparam name="TDestination">目标类型</typeparam>
        /// <param name="tSource">源数据</param>
        /// <param name="configurationExpression">类型</param>
        /// <returns></returns>
        public static TDestination MapsterTo<TSource, TDestination>(TSource tSource, TypeAdapterConfig typeAdapterConfig) where TSource : class where TDestination : class
        {
            if (tSource == null) return default;

            //var typeAdapterConfig = new TypeAdapterConfig();
            //typeAdapterConfig.ForType<MapsterTestTable_ViewModel, MapsterTestTable>()
            //    .Map(member => member.DestName, source => source.Name)  // 指定字段一一对应
            //    .Map(member => member.Birthday, source => source.Birthday.ToString("yy-MM-dd HH:mm"))                              // 指定字段,并转化指定的格式
            //    .Map(member => member.Age, source => source.Age > 5)                                                               // 条件赋值
            //    .Ignore(member => member.A1)                                                                                       // 忽略该字段,不给该字段赋值
            //    .IgnoreNullValues(true)                                                                                            // 忽略空值映射
            //    .IgnoreAttribute(typeof(DataMemberAttribute))                                                                      // 忽略指定特性的字段
            //    .Map(member => member.A3, source => source.Name + source.Age * 3 + source.Birthday.ToString("d"))                  // 可以自己随意组合赋值
            //    .NameMatchingStrategy(NameMatchingStrategy.IgnoreCase);                                                            // 忽略字段名称的大小写

            var mapper = new Mapper(typeAdapterConfig);  // 可以自己随意组合赋值
            return mapper.Map<TDestination>(tSource);
        }
        #endregion 实体映射

            #region 列表映射
            /// <summary>
            /// 3、集合列表类型映射,默认字段名字一一对应
            /// </summary>
            /// <typeparam name="TSource">源类型</typeparam>
            /// <typeparam name="TDestination">目标类型</typeparam>
            /// <param name="source">源数据</param>
            /// <returns></returns>
        public static List<TDestination> MapsterToList<TSource, TDestination>(List<TSource> sources) where TSource : class where TDestination : class
        {
            if (sources == null) return new List<TDestination>();

            return sources.Adapt<List<TDestination>>();
        }
        #endregion 列表映射

        
    }

    /// <summary>
    /// Mapster映射帮助类 - 示例(未测试)
    /// Mapster 版本12.0.0
    /// </summary>
    public class MapsterHelperTeatDemo
    {
        #region 实体映射
        /// <summary>
        /// 1、类型映射_默认字段一一对应
        /// </summary>
        public void MapsterToDemo()
        {
            MapsterTestTable_ViewModel tableTest1 = new();

            MapsterTestTable tableTest = MapsterHelper.MapsterTo<MapsterTestTable_ViewModel, MapsterTestTable>(tableTest1);
        }

        /// <summary>
        /// 2、类型映射
        /// ① 字段名称不对应
        /// ② 类型转化
        /// ③ 字段省略
        /// ④ 字段名称或类型不对应
        /// ⑤ 条件赋值或null处理
        /// ⑥ 组合赋值
        /// </summary>
        public void MapsterTo2Demo()
        {
            MapsterTestTable_ViewModel tableTest1 = new();
            // 这里是语句,不是无用的数据;
            var typeAdapterConfig = new TypeAdapterConfig();
            typeAdapterConfig.ForType<MapsterTestTable_ViewModel, MapsterTestTable>()
                .Map(member => member.DestName, source => source.Name)  // 指定字段一一对应
                .Map(member => member.Birthday, source => source.Birthday.ToString("yy-MM-dd HH:mm"))                              // 指定字段,并转化指定的格式
                .Map(member => member.Age, source => source.Age > 5)                                                               // 条件赋值
                .Ignore(member => member.A1)                                                                                       // 忽略该字段,不给该字段赋值
                .IgnoreNullValues(true)                                                                                            // 忽略空值映射
                .IgnoreAttribute(typeof(DataMemberAttribute))                                                                      // 忽略指定特性的字段
                .Map(member => member.A3, source => source.Name + source.Age * 3 + source.Birthday.ToString("d"))                  // 可以自己随意组合赋值
                .NameMatchingStrategy(NameMatchingStrategy.IgnoreCase);                                                            // 忽略字段名称的大小写

            MapsterTestTable tableTest = MapsterHelper.MapsterTo<MapsterTestTable_ViewModel, MapsterTestTable>(tableTest1, typeAdapterConfig);
        }
        #endregion 实体映射

        #region 列表映射
        /// <summary>
        /// 3、集合列表类型映射,默认字段名字一一对应
        /// </summary>
        public void MapsterToListDemo()
        {
            List<MapsterTestTable_ViewModel> tableTestVMs = new();

            List<MapsterTestTable> tableTests = MapsterHelper.MapsterToList<MapsterTestTable_ViewModel, MapsterTestTable>(tableTestVMs);
        }
        #endregion 列表映射
    }

    #region MapsterHelper测试示例用
    public class MapsterTestTable_ViewModel
    {
        public string Name { get; set; }
        public DateTime Birthday { get; set; }
        public int Age { get; set; }

        public DateTime A4 { get; set; }
    }

    // [AdaptTo("MapsterTestTable_ViewModel"), GenerateMapper]  // 显示声明式映射写法
    public class MapsterTestTable
    {
        public string DestName { get; set; }
        public DateTime Birthday { get; set; }
        public int Age { get; set; }

        //[AdaptIgnore]  // 显示声明式忽略该字段
        public string A1 { get; set; }
        public string A2 { get; set; }
        public string A3 { get; set; }
    }
    #endregion MapsterHelper测试示例用
}