C#-对象映射器(一)-AutoMapper映射帮助类

一、AutoMapper简介

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

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

  • IMapping接口:定义了实体类和数据库表之间的映射关系。
  • Mapper接口:定义了实体类映射到数据库表中的具体实现。
  • Query接口:定义了查询语句的规则。
  • DataContext接口:定义了数据上下文的接口。
  • Configuration接口:定义了配置文件的接口。
 

二、AutoMapper帮助类

/**
*┌──────────────────────────────────────────────────────────────┐
*│ 描    述:AutoMapper映射帮助类-基础使用 (AutoMapper 12.0.0)                                              
*│ 作    者:执笔小白                                              
*│ 版    本:1.0                                       
*│ 创建时间:2023-01-14 15:40:56                            
*└──────────────────────────────────────────────────────────────┘
*┌──────────────────────────────────────────────────────────────┐
*│ 命名空间: Util.ObjMapperUtil                         
*│ 类    名:AutoMapperHelper、AutoMapperHelperTeat                                    
*└──────────────────────────────────────────────────────────────┘
*/
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace fly_webapi.Util.ObjMapperUtil
{

    /// <summary>
    /// AutoMapper映射帮助类
    /// AutoMapper 版本12.0.0
    /// </summary>
    public static class AutoMapperHelper
    {
        #region 实体映射
        /// <summary>
        /// 1、类型映射_默认字段一一对应
        /// </summary>
        /// <typeparam name="TSource">源类型</typeparam>
        /// <typeparam name="TDestination">目标类型</typeparam>
        /// <param name="tSource">源数据</param>
        /// <returns></returns>
        public static TDestination AutoMapperTo<TSource, TDestination>(TSource tSource) where TSource : class where TDestination : class
        {
            if (tSource == null) return default;

            var config = new MapperConfiguration(cfg => cfg.CreateMap<TSource, TDestination>());

            var mapper = config.CreateMapper();
            return mapper.Map<TDestination>(tSource);
        }

        /// <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 AutoMapperTo<TSource, TDestination>(TSource tSource, MapperConfigurationExpression configurationExpression) where TSource : class where TDestination : class
        {
            if (tSource == null) return default;

            //var config = new MapperConfiguration(cfg => cfg.CreateMap<TSource, TDestination>()
            //    .ForMember(d => d.DestName, opt => opt.MapFrom(s => s.Name))  // 指定字段一一对应
            //    .ForMember(d => d.Birthday, opt => opt.MapFrom(src => src.Birthday.ToString("yy-MM-dd HH:mm")))          // 指定字段,并转化指定的格式
            //    .ForMember(d => d.Age, opt => opt.Condition(src => src.Age > 5))                                         // 条件赋值
            //    .ForMember(d => d.A1, opt => opt.Ignore())                                                               // 忽略该字段,不给该字段赋值
            //    .ForMember(d => d.A1, opt => opt.NullSubstitute("Default Value"))                                        // 如果源字段值为空,则赋值为 Default Value
            //    .ForMember(d => d.A1, opt => opt.MapFrom(src => src.Name + src.Age * 3 + src.Birthday.ToString("d"))));  // 可以自己随意组合赋值

            var config = new MapperConfiguration(configurationExpression);  // 可以自己随意组合赋值

            var mapper = config.CreateMapper();
            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> AutoMapperToList<TSource, TDestination>(List<TSource> sources) where TSource : class where TDestination : class
        {
            if (sources == null) return new List<TDestination>();

            var config = new MapperConfiguration(cfg => cfg.CreateMap<TSource, TDestination>());

            var mapper = config.CreateMapper();
            return mapper.Map<List<TDestination>>(sources);
        }
        #endregion 列表映射
    }

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

            AutoMapperTableTest tableTest = AutoMapperHelper.AutoMapperTo<AutoMapperTableTest_ViewModel, AutoMapperTableTest>(tableTest1);
        }

        /// <summary>
        /// 2、类型映射
        /// ① 字段名称不对应
        /// ② 类型转化
        /// ③ 字段省略
        /// ④ 字段名称或类型不对应
        /// ⑤ 条件赋值或null处理
        /// ⑥ 组合赋值
        /// </summary>
        public void AutoMapperTo2Demo()
        {
            AutoMapperTableTest_ViewModel tableTest1 = new();
            // 这里是语句,不是无用的数据;
            MapperConfigurationExpression mapperConfiguration = new();
            var config = new MapperConfiguration(cfg => cfg.CreateMap<AutoMapperTableTest_ViewModel, AutoMapperTableTest>()
                .ForMember(d => d.DestName, opt => opt.MapFrom(s => s.Name))                                             // 指定字段一一对应
                .ForMember(d => d.Birthday, opt => opt.MapFrom(src => src.Birthday.ToString("yy-MM-dd HH:mm")))          // 指定字段,并转化指定的格式
                .ForMember(d => d.Age, opt => opt.Condition(src => src.Age > 5))                                         // 条件赋值
                .ForMember(d => d.A1, opt => opt.Ignore())                                                               // 忽略该字段,不给该字段赋值
                .ForMember(d => d.A2, opt => opt.NullSubstitute("Default Value"))                                        // 如果源字段值为空,则赋值为 Default Value
                .ForMember(d => d.A3, opt => opt.MapFrom(src => src.Name + src.Age * 3 + src.Birthday.ToString("d"))));  // 可以自己随意组合赋值

            AutoMapperTableTest tableTest = AutoMapperHelper.AutoMapperTo<AutoMapperTableTest_ViewModel, AutoMapperTableTest>(tableTest1, mapperConfiguration);
        }
        #endregion 实体映射

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

            List<AutoMapperTableTest> tableTests = AutoMapperHelper.AutoMapperToList<AutoMapperTableTest_ViewModel, AutoMapperTableTest>(tableTestVMs);
        }
        #endregion 列表映射
    }

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

    public class AutoMapperTableTest
    {
        public string DestName { get; set; }
        public DateTime Birthday { get; set; }
        public int Age { get; set; }
        public string A1 { get; set; }
        public string A2 { get; set; }
        public string A3 { get; set; }
    }
    #endregion AutoMapperHelper测试示例用
}
posted @   ꧁执笔小白꧂  阅读(1045)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
历史上的今天:
2022-01-17 vue与nvue的区别
2022-01-17 html标签和uni-app内置组件的映射表
2022-01-17 uni-app打包64位的安卓app
2020-01-17 C++ const,static,extern,rand()等一些例题分析
点击右上角即可分享
微信分享提示