在.NET框架中,对象映射(Object Mapping)是一个重要的概念。它允许将不同的数据存储格式(如XML、JSON、文本文件等)映射到对象,并在不同的应用程序之间共享这些数据。而Mapster则是一个快速、小巧、功能强大的对象映射框架,它为.NET开发者提供了方便和高效的数据映射方式。
除了实体类与数据格式之间的映射,Mapster框架还支持从不同的数据源读取数据,并将其映射到实体类中。这个过程包括从数据库中读取数据、从文件中读取数据、从网络上读取数据等等。在这个过程中,Mapster提供了丰富的数据类型支持,包括自定义类型和嵌套类型。
Mapster框架还提供了许多方便的工具,如查询语句的映射、映射错误的处理等等。在使用Mapster框架时,开发者只需要编写简单的代码,就可以轻松地完成数据映射的工作。
nuget 安装Mapster 库
我们先实现一个简单对像的映射。
Adapt<TSource, TDestination>(this TSource source)
:将一个源对象映射到目标对象,根据属性名称和类型进行自动映射。Adapt<TDestination>(this object source)
:将一个对象映射到目标对象,根据属性名称和类型进行自动映射。注意,该方法适用于单个对象的映射。AdaptTo<TSource, TDestination>(this IEnumerable<TSource> source)
:将一个源对象集合映射到目标对象集合,根据属性名称和类型进行自动映射。AdaptTo<TDestination>(this IEnumerable<object> source)
:将一个对象集合映射到目标对象集合,根据属性名称和类型进行自动映射。注意,该方法适用于多个对象的映射。ForType<TDestination>(this TypeAdapterConfig<TSource, TDestination> config)
:为特定的源类型和目标类型配置映射规则,可以在此处自定义属性映射和转换规则。Mapster.TypeAdapterConfig.GlobalSettings
:全局配置选项,可以通过此对象进行全局的映射配置,如默认忽略空引用等。UseDestinationValue
:在映射过程中保留目标对象已有的值。IgnoreNullValues
:忽略源对象中的空引用属性,不映射到目标对象。Compile
:将配置的映射规则编译成可执行的委托,加快映射的速度。TransformUsing
:使用自定义的转换函数,对属性值进行特殊处理。Person类
C#public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public DateTime Birthday { get; set;}
}
Student 类
C#public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public DateTime Birthday { get; set; }
public string ClassName { get; set; }
}
我们将Person类的一个实例映射到Student的一个实例
C#private void btnConvert_Click(object sender, EventArgs e)
{
Person p1=new Person();
p1.Name = "张三";
p1.Age = 1;
p1.Birthday = DateTime.Parse("2022-1-1");
Student s1= p1.Adapt<Student>();
}
C#public partial class Form1 : Form
{
JsonSerializerOptions options = new JsonSerializerOptions();
public Form1()
{
InitializeComponent();
//防止中文编码
options.Encoder = System.Text.Encodings.Web
.JavaScriptEncoder.Create(UnicodeRanges.All);
}
private void btnConvert_Click(object sender, EventArgs e)
{
Person p1=new Person();
p1.Name = "张三";
p1.Age = 1;
p1.Birthday = DateTime.Parse("2022-1-1");
p1.Job = "组长";
//手动映射字段
TypeAdapterConfig<Person, Student>
.NewConfig()
.AddDestinationTransform((string x) => !string.IsNullOrWhiteSpace(x) ? x : " ") // 空值替换
.Map(x => x.Role, s => s.Job);
var s1 = p1.Adapt<Student>();
MessageBox.Show(System.Text.Json.JsonSerializer.Serialize(s1, options));
}
}
在实际为业务中用的比较多的是将列表映射到其它列表。
C#Person p1=new Person();
p1.Name = "张三";
p1.Age = 1;
p1.Birthday = DateTime.Parse("2022-1-1");
p1.Job = "组长";
List<Person> persons = new List<Person>();
persons.Add(p1);
var students= persons.Adapt<List<Student>>();
增加一个IdNo,在转Student时,替换成*
C#//手动映射字段
TypeAdapterConfig<Person, Student>
.NewConfig()
.AddDestinationTransform((string x) => !string.IsNullOrWhiteSpace(x) ? x : " ") // 空值替换
.Map(x => x.Role, s => s.Job)
.Map(x => x.IdNo, s => s.IdNo.Replace("1", "*"));
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!