当前位置: 首页 > news >正文

C#--Mapster(高性能映射)用法

1.Nuget安装Mapster包引用

2.界面XAML部分

<Window x:Class="WpfApp35.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WpfApp35"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"><Grid><Button Content="1.简单映射" HorizontalAlignment="Left" Margin="345,145,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1" Height="52"/><Button Content="2.复杂映射" HorizontalAlignment="Left" Margin="345,235,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_2" Height="52"/><Button Content="3.映射扩展" HorizontalAlignment="Left" Margin="345,320,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_3" Height="52"/></Grid>
</Window>

3.脚本.cs部分 

using Mapster;
using MapsterMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Expression = System.Linq.Expressions.Expression;namespace WpfApp35
{/// <summary>/// MainWindow.xaml 的交互逻辑/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();// 全局配置//TypeAdapterConfig.GlobalSettings.Default.CamelCase(true); // 将属性名称转换为小驼峰命名}//软件框架搭建  wpf+efcore+ct(CommunityToolkit)+s7net+mapster//1.简单映射private void Button_Click_1(object sender, RoutedEventArgs e){//阶段一  简单使用阶段部分  Student==>StudentDto//上面简单映射,但是类StudentDto中的CourceName属性没有被映射,通过下面方法可对属性设置匹配关系,给CourceName属性映射Student stu = new Student();stu.AGE = 25;stu.ID = "1";stu.CID = "321281199505290919";stu.NAME = "陈兆杰";Cource cource = new Cource();cource.ID = "1";cource.CourceName = "数学";cource.Grade = 80.56;stu.Cource = cource;StudentDto stuDto = new StudentDto();{//方法一:stuDto = stu.Adapt<StudentDto>();//stu实例映射为StudentDto类型MessageBox.Show($"stuDto.CourceName: {stuDto.CourceName}");//方法二:stu.Adapt(stuDto);//stu实例映射为stuDto实例,相同的名称字段属性将会自动映射MessageBox.Show($"stuDto.CourceName: {stuDto.CourceName}");//方法三:IMapper mapper = new Mapper();stuDto = mapper.Map<StudentDto>(stu);// stu实例映射为StudentDto类型MessageBox.Show($"stuDto.CourceName: {stuDto.CourceName}");//方法四:mapper.Map(stu, stuDto);//stu实例映射为stuDto实例,相同的名称字段属性将会自动映射MessageBox.Show($"stuDto.CourceName: {stuDto.CourceName}");}}//2.复杂映射private void Button_Click_2(object sender, RoutedEventArgs e){//阶段二  复杂映射  Student==>StudentDtoStudent stu = new Student();stu.AGE = 25;stu.ID = "1";stu.CID = "321281199505290919";stu.NAME = "陈兆杰";Cource cource = new Cource();cource.ID = "1";cource.CourceName = "数学";cource.Grade = 80.56;stu.Cource = cource;StudentDto stuDto = new StudentDto();{TypeAdapterConfig config = new TypeAdapterConfig();//建立映射关系一, NewConfig 删除任何现有配置{//配置里面设置强行绑定项部分config.NewConfig<Student, StudentDto>().Map(dto => dto.ID, d => d.ID).Map(dto => dto.NAME, d => d.NAME).Map(dto => dto.CourceName, s => s.Cource.CourceName);}//建立映射关系二,而 ForType 创建或增强配置。{//        config.ForType<Student, StudentDto>()//.Map(dto => dto.ID, d => d.ID).Map(dto => dto.NAME, d => d.NAME).Map(dto => dto.CourceName, s => s.Cource.CourceName);}stuDto = stu.Adapt<StudentDto>(config);//根据config配置,映射stu实体为StudentDto类型MessageBox.Show($"stuDto.CourceName: {stuDto.CourceName}");}}//映射扩展private void Button_Click_3(object sender, RoutedEventArgs e){Student stu = new Student{age = 25,id = 1,name = "陈兆杰111",classes = classes};StudentDto StuDto1 = ExpressionMapper.Mapper(stu, s => new StudentDto{classesName = s.classes.name,});}/// <summary>/// 可以处理复杂映射/// </summary>/// <typeparam name="TIn">输入类</typeparam>/// <typeparam name="TOut">输出类</typeparam>/// <param name="expression">表达式目录树,可以为null</param>/// <param name="tIn">输入实例</param>/// <returns></returns>public static TOut Mapper<TIn, TOut>(TIn tIn, Expression<Func<TIn, TOut>> expression = null){ParameterExpression parameterExpression = null;List<MemberBinding> memberBindingList = new List<MemberBinding>();parameterExpression = Expression.Parameter(typeof(TIn), "p");if (expression != null){parameterExpression = expression.Parameters[0];if (expression.Body != null){memberBindingList.AddRange((expression.Body as MemberInitExpression).Bindings);}}foreach (var item in typeof(TOut).GetProperties()){if (typeof(TIn).GetProperty(item.Name) != null){MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name));MemberBinding memberBinding = Expression.Bind(item, property);memberBindingList.Add(memberBinding);}if (typeof(TIn).GetField(item.Name) != null){MemberExpression property = Expression.Field(parameterExpression, typeof(TIn).GetField(item.Name));MemberBinding memberBinding = Expression.Bind(item, property);memberBindingList.Add(memberBinding);}}foreach (var item in typeof(TOut).GetFields()){if (typeof(TIn).GetField(item.Name) != null){MemberExpression property = Expression.Field(parameterExpression, typeof(TIn).GetField(item.Name));MemberBinding memberBinding = Expression.Bind(item, property);memberBindingList.Add(memberBinding);}if (typeof(TIn).GetProperty(item.Name) != null){MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name));MemberBinding memberBinding = Expression.Bind(item, property);memberBindingList.Add(memberBinding);}}MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray());Expression<Func<TIn, TOut>> lambda = Expression.Lambda<Func<TIn, TOut>>(memberInitExpression, new ParameterExpression[]{parameterExpression});Func<TIn, TOut> func = lambda.Compile();//获取委托return func.Invoke(tIn);}}public class Student{public string ID { get; set; }public string NAME { get; set; }public int AGE { get; set; }public string CID { get; set; }public Cource Cource { get; set; }}public class Cource{public string ID { get; set; }public string CourceName { get; set; }public double Grade { get; set; }}public class StudentDto{public string ID { get; set; }public string NAME { get; set; }public string CourceName { get; set; }}
}

4.小结 

        Mapster库是一个用于对象映射的工具,它的作用就像是帮助你把一个对象中的数据复制到另一个对象中。简单来说,当你需要把一个类的数据转换成另一个类的数据时,Mapster可以帮助你快速、方便地实现这个转换过程,省去了手动赋值的繁琐工作。这对于在应用程序中处理不同类型对象之间的数据转换非常有用,让你可以更轻松地管理和操作数据。

应用场景:

        当你开发一个电子商务网站时,假设你有一个名为 Product 的类,表示网站上的商品信息,包括商品名称、价格、描述等属性。另外你还有一个名为 ProductViewModel 的类,表示在网页上展示商品信息所需的属性,比如显示的商品名称、价格、缩略图等。

你可以使用 Mapster 库来处理这两个类之间的数据映射。比如,当你从数据库中查询到了 Product 对象,想要在网页上展示商品信息时,你可以使用 Mapster 来将 Product 对象映射成 ProductViewModel 对象,这样就可以方便地在网页上展示商品信息,而不需要手动复制每个属性的数值。

http://www.lryc.cn/news/356823.html

相关文章:

  • mysql实战——Mysql8.0高可用之双主+keepalived
  • 关于同一个地址用作两个不同页面时,列表操作栏按钮混淆状态
  • Oracle段延迟分配(Deferred Segment Creation)解析
  • Linux:IPC - System V
  • Laravel 图片添加水印
  • 嵌入式进阶——矩阵键盘
  • 请说出vue.cli项目中src目录每个文件夹和文件的用法
  • 【MySQL精通之路】InnoDB磁盘I/O和文件空间管理(11)
  • 基于springboot+html的二手交易平台(附源码)
  • 正点原子[第二期]Linux之ARM(MX6U)裸机篇学习笔记-24.3,4 SPI驱动实验-I.MX6U SPI 寄存器
  • 【Pandas】数据处理方法
  • 【ArcGIS For JS】前端geojson渲染行政区划图层并加标签
  • Spring AOP原理详解:动态代理与实际应用
  • 死锁的四个必要条件
  • 源网络地址转换SNAT
  • 【算法】平衡二叉搜索树的左旋和右旋
  • 介绍Django Ninja框架
  • 使用uniapp内置组件checkbox-group所遇到的问题
  • 嵌入式学习记录5.23(超时检测、抓包分析)
  • Linux|如何在 awk 中使用流控制语句
  • OceanBase数据库诊断调优,与高可用架构——【DBA从入门到实践】第八期
  • LLVM技术在GaussDB等数据库中的应用
  • 【SQL学习进阶】从入门到高级应用(三)
  • 迷你手持小风扇哪个品牌续航强?五款强续航迷你手持小风扇推荐!
  • SpringBoot 微服务中怎么获取用户信息 token
  • npm包-fflate
  • 华为WLAN无线组网技术与解决方案
  • 闲鱼电商运营高级课程,一部手机学会闲鱼开店赚钱
  • Yann LeCun 和 Elon Musk 就 AI 监管激烈交锋
  • C++重点基础知识汇总大全