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==>StudentDto
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();
{
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 对象,这样就可以方便地在网页上展示商品信息,而不需要手动复制每个属性的数值。