当前位置:网站首页>4. Object mapping Mapstercover
4. Object mapping Mapstercover
2022-07-02 00:03:00 【InfoQ】
Preface
- Mapster
- AutoMapper
AutoMapper
Mapster
Mapster
Mapster
Masa
Mapster
Mapster brief introduction
Mapster
AutoMapper
Mapster
preparation
- 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();
}

Mapster
Mapster
Masa
What is? Masa.Contrib.Data.Mapping.Mapster?
Masa.Contrib.Data.Mapping.Mapster
Mapster
Mapster
Mapping 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.Mapster
Mapster
summary
Masa.Contrib.Data.Mapping.Mapster
Mapster
Masa
BuildingBlocks
IMapper
Mapster
AutoMapper
AutoMapper
IMapper
BuildingBlocks
Source code of this chapter
Open source address

边栏推荐
- JPA handwritten SQL, received with user-defined entity classes
- Selectively inhibiting learning bias for active sampling
- ADO. Net SqlDataAdapter object
- Is it safe to choose mobile phone for stock trading account opening in Beijing?
- .env.xxx 文件,加了常量,卻undefined
- Windows10 install WSL (I) (wslregisterdistribution error)
- openwrt 开启KV漫游
- Relatively easy to understand PID understanding
- Deep learning | three concepts: epoch, batch, iteration
- Niuke - Practice 101 - reasoning clown
猜你喜欢
UDS bootloader of s32kxxx bootloader
Selectively inhibiting learning bias for active sampling
时间复杂度与空间复杂度
LDR6035智能蓝牙音响可充可放(5.9.12.15.20V)快充快放设备充电
The essence of software architecture
比较通俗易懂的PID理解
Multi table operation - one to one, one to many and many to many
[QT] solve the problem that QT MSVC 2017 cannot compile
第六章 数据流建模
Why does blocprovider feel similar to provider?
随机推荐
Download the online video m3u8 tutorial
写给当前及未来博士研究生一些建议整理分享
[C #] dependency injection and Autofac
[untitled]
使用 pair 做 unordered_map 的键值
algolia 搜索需求,做的快自闭了...
第六章 数据流建模
Graduation season is both a farewell and a new beginning
Openvino model performance evaluation tool DL workbench
LDR6035智能蓝牙音响可充可放(5.9.12.15.20V)快充快放设备充电
The difference between timer and scheduledthreadpoolexecutor
【QT】Qt 使用MSVC2017找不到编译器的解决办法
ADO. Net SqlDataAdapter object
记录一下大文件上传偶然成功偶然失败问题
const // It is a const object... class nullptr_ t
起床困难综合症(按位贪心)
openwrt 开启KV漫游
Review data desensitization system
2021 robocom world robot developer competition - semi finals of higher vocational group
ADO.NET之sqlCommand对象