public class Student
{
public string FirstName {get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Address { get; set; }
public string Gender {get; set; }
}
StudentDto
public class StudentDto
{
public string FullName {get; set; }
public int Age { get; set; }
public string Gender {get; set; }
}
传统赋值模式代码如下:
var student = new Student()
{
FirstName = "Monk",
LastName = "Soul",
Age = 27,
Address = "广东省珠海市香洲区吉大路",
Gender = "男"
};
// 赋值
var studentDto = new StudentDto()
{
FullName = student.FirstName + student.LastName,
Age = student.Age,
Gender = student.Gender
}
Hoa Framework 内置了将类似 GROUP_ID->GroupId和GroupId->GROUP_ID两种映射方式,这是 Mapster 默认不具备的功能。
配置Hoa.Application.ManualMapper.cs如下:
using Mapster;
using System.Text;
namespace Hoa.Application.Authorization.Dtos
{
public class Mapper : IRegister
{
public void Register(TypeAdapterConfig config)
{
config.ForType<SignInInput, SignInInput2>()
.ConvertSourceMemberUnderlineSplitNameToCamelCase(); // 支持:GROUP_ID -> GroupId 方式
config.ForType<SignInInput2, SignInInput>()
.ConvertSourceMemberCamelCaseNameToUnderlineSplit(); // 支持:GroupId -> GROUP_ID 方式
}
}
}
数据库实体映射说明
将 EF Core 查询的结果集映射到 Dto 中。
using (MyDbContext context = new MyDbContext())
{
// 不使用 Mapster 时候
var destinations = context.Sources.Select(c => new Destination {
Id = p.Id,
Name = p.Name,
Surname = p.Surname,
....
})
.ToList();
}
using (MyDbContext context = new MyDbContext())
{
// 使用 Mapster 后
var destinations = context.Sources.ProjectToType<Destination>().ToList();
}
将 Dto 映射到已存在的 Entity
var entity = _testRepository.GetFirstOrDefault(predicate: u =>u.Id == 1);
var dto = new Dto() { Name = "Monk", Age = 27};
dto.Adapt(entity); // 这时,Entity会自动更新 Name和Age属性,其他的保持不变