当前位置:网站首页>4. Object mapping Mapstercover
4. Object mapping Mapstercover
2022-07-02 00:03:00 【InfoQ】
Preface
- Mapster
- AutoMapper
AutoMapperMapsterMapsterMapsterMasaMapsterMapster brief introduction
MapsterAutoMapperMapsterpreparation
- Create a new console project
Assignment.Mapster, And installMapster
dotnet add package Mapster --version 7.3.0
Map to new object
- The new class
UserDto
public class UserDto
{
public int Id { get; set; }
public string Name { get; set; }
public uint Gender { get; set; }
public DateTime BirthDay { get; set; }
}
- Create a new anonymous object , As the source of the object to be converted
var user = new
{
Id = 1,
Name = "Tom",
Gender = 1,
BirthDay = DateTime.Parse("2002-01-01")
};
- take user The source object is mapped to the target object (UserDto)
var userDto = user.Adapt<UserDto>();
Console.WriteLine($" Map to new object ,Name: {userDto.Name}");

data type
Basic types
- Provide the function of type mapping , similar Convert.ChangeType()
string res = "123";
decimal i = res.Adapt<decimal>(); //equal to (decimal)123;
Console.WriteLine($" The result is :{i == int.Parse(res)}");

Enumeration type
- Map enumerations to numeric types , It also supports string to enumeration and enumeration to string mapping , Than .NET The default implementation of is twice as fast
var fileMode = "Create, Open".Adapt<FileMode>();// be equal to FileMode.Create | FileMode.Open
Console.WriteLine($" The result of enumeration type conversion is :{fileMode == (FileMode.Create | FileMode.Open)}");

Queryable Expand
- The new class
UserDbContext
using Assignment.Mapster.Domain;
using Microsoft.EntityFrameworkCore;
namespace Assignment.Mapster.Infrastructure;
public class UserDbContext : DbContext
{
public DbSet<User> User { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var dataBaseName = Guid.NewGuid().ToString();
optionsBuilder.UseInMemoryDatabase(dataBaseName);// Use memory database , Convenient test
}
}
- The new class
User
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public uint Gender { get; set; }
public DateTime BirthDay { get; set; }
public DateTime CreationTime { get; set; }
public User()
{
CreationTime = DateTime.Now;
}
}
- Using a Queryable Extension method of
ProjectToType
using (var dbContext = new UserDbContext())
{
dbContext.Database.EnsureCreated();
dbContext.User.Add(new User()
{
Id = 1,
Name = "Tom",
Gender = 1,
BirthDay = DateTime.Parse("2002-01-01")
});
dbContext.SaveChanges();
var userItemList = dbContext.User.ProjectToType<UserDto>().ToList();
}

MapsterMapsterMasaWhat is? Masa.Contrib.Data.Mapping.Mapster?
Masa.Contrib.Data.Mapping.MapsterMapsterMapsterMapping rule
- When the target object does not have a constructor : Use an empty constructor , Mapping to fields and attributes .
- Multiple constructors exist for the target object : Get the best constructor mapping
- Best constructor : The number of constructor parameters of the target object is found in descending order , The parameter names are consistent ( Case insensitive ) And the parameter type is consistent with the source object attribute
preparation
- Create a new console project
Assignment.Masa.Mapster, And installMasa.Contrib.Data.Mapping.Mapster,Microsoft.Extensions.DependencyInjection
dotnet add package Masa.Contrib.Data.Mapping.Mapster --version 0.4.0-rc.4
dotnet add package Microsoft.Extensions.DependencyInjection --version 6.0.0
- The new class
OrderItem
public class OrderItem
{
public string Name { get; set; }
public decimal Price { get; set; }
public int Number { get; set; }
public OrderItem(string name, decimal price) : this(name, price, 1)
{
}
public OrderItem(string name, decimal price, int number)
{
Name = name;
Price = price;
Number = number;
}
}
- The new class
Order
public class Order
{
public string Name { get; set; }
public decimal TotalPrice { get; set; }
public List<OrderItem> OrderItems { get; set; }
public Order(string name)
{
Name = name;
}
public Order(string name, OrderItem orderItem) : this(name)
{
OrderItems = new List<OrderItem> { orderItem };
TotalPrice = OrderItems.Sum(item => item.Price * item.Number);
}
}
- Modify the class
Program
using Assignment.Masa.Mapster.Domain.Aggregate;
using Masa.BuildingBlocks.Data.Mapping;
using Masa.Contrib.Data.Mapping.Mapster;
using Microsoft.Extensions.DependencyInjection;
Console.WriteLine("Hello Masa Mapster!");
IServiceCollection services = new ServiceCollection();
services.AddMapping();
var request = new
{
Name = "Teach you to learn Dapr ……",
OrderItem = new OrderItem("Teach you to learn Dapr hand by hand", 49.9m)
};
var serviceProvider = services.BuildServiceProvider();
var mapper = serviceProvider.GetRequiredService<IMapper>();
var order = mapper.Map<Order>(request);
Console.WriteLine($"{nameof(Order.TotalPrice)} is {order.TotalPrice}");// Console output 49.9
Console.ReadKey();

How to achieve
Masa.Contrib.Data.Mapping.MapsterMapstersummary
Masa.Contrib.Data.Mapping.MapsterMapsterMasaBuildingBlocksIMapperMapsterAutoMapperAutoMapperIMapperBuildingBlocksSource code of this chapter
Open source address

边栏推荐
猜你喜欢

GCC compilation

GaussDB(for MySQL) :Partial Result Cache,通过缓存中间结果对算子进行加速

Key points of security agreement

The essence of software architecture

Why does blocprovider feel similar to provider?

Asp .NetCore 微信订阅号自动回复之文本篇
![[embedded system course design] a single key controls the LED light](/img/c9/076618208bbab0b95faa5a7e644a07.png)
[embedded system course design] a single key controls the LED light

Openvino model performance evaluation tool DL workbench

Graduation season is both a farewell and a new beginning

Windows10 install WSL (I) (wslregisterdistribution error)
随机推荐
Review data desensitization system
SQL数据分析之窗口排序函数rank、dense_rank、raw_number与lag、lead窗口偏移函数【用法整理】
【QT】Qt 使用MSVC2017找不到编译器的解决办法
微信小程序缓存过期时间的相关设置(推荐)
Using SqlCommand objects in code
【QT】测试Qt是否能连接上数据库
在长城证券上买基金安全吗?
leetcode96不同的二叉搜索樹
Windows 7 安装MYSQL 错误:1067
[C #] dependency injection and Autofac
The origin of usb-if Association and various interfaces
[embedded system course design] a single key controls the LED light
[es practice] safe operation mode on ES
Shell process control
ADO. Net SqlCommand object
vs2015 AdminDeployment.xml
边缘计算概述
SQL数据分析之流程控制语句【if,case...when详解】
ConcurrentSkipListMap——跳表原理
Linux CentOS7安装Oracle11g的超完美新手教程