ASP .NET Core 使用Mapster 进行DTO映射
安装Mapster
Install-Package Mapster
基本使用
新建以下实体类
public class Person
{
public string? Title { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
public DateTime? DateOfBirth { get; set; }
}
public class PersonDto
{
public string? Title { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
}
public class PersonShortInfoDto
{
public string? Title { get; set; }
public string? FullName { get; set; }
public int? Age { get; set; }
public string? FullAddress { get; set; }
}
添加数据
var people= new Person()
{
Title = "Mr.",
FirstName = "Peter",
LastName = "Pan",
DateOfBirth = new DateTime(2000, 1, 1)
};
Adapt映射
var s = 123.Adapt<string>(); // 等同于: 123.ToString();
var i = "123".Adapt<int>(); // 等同于: int.Parse("123");
PersonDto pDto = people.Adapt<PersonDto>();
//转换的是值类型时避免不必要的装箱/拆箱
PersonDto pDto = people.Adapt<Person, PersonDto>();
PersonDto pDto = people.Adapt(new PersonDto());
IMapper映射
Program.cs
注入IMapper
builder.Services.AddScoped<IMapper, Mapper>();
使用
private readonly IMapper _mapper;
public WeatherForecastController(IMapper mapper)
{
_mapper = mapper;
}
public void Dto()
{
var people = new Person() { Title = "Mr" };
var pDto = _mapper.Map<PersonDto>(people);
}
自定义映射关系
//Person是数据源(src)
TypeAdapterConfig<Person, PersonShortInfoDto>
.NewConfig()
//忽略Title
.Ignore(infodto => infodto.Title)
//映射FullName并重新赋值
.Map(infodto => infodto.FullName, src => $"{src.Title} {src.FirstName} {src.LastName}")
//DateOfBirth有值时才会进行映射
.Map(infodto => infodto.Age,
src => DateTime.Now.Year - src.DateOfBirth.Value.Year,
srcCond => srcCond.DateOfBirth.HasValue);
映射
PersonShortInfoDto pDto = people.Adapt<PersonShortInfoDto>();
全局配置
public static void RegisterMapsterConfiguration(this IServiceCollection services)
{
TypeAdapterConfigTypeAdapterConfig<Person, PersonShortInfoDto>....
}
使用TypeAdapterConfig
TypeAdapterConfig config = new TypeAdapterConfig();
config.ForType<Person, PersonShortInfoDto>()
.Ignore(dto => dto.Title)
.Map(dto => dto.FullName, src => $"{src.Title} {src.FirstName} {src.LastName}")
.Map(dto => dto.Age, src => DateTime.Now.Year - src.DateOfBirth.Value.Year, srcCond => srcCond.DateOfBirth.HasValue);
PersonShortInfoDto pDto = people.Adapt<PersonShortInfoDto>(config);
忽略字段
使用TypeAdapterConfig
进行配置
TypeAdapterConfig<Person, PersonShortInfoDto>
.NewConfig()
//忽略Title
.Ignore(infodto => infodto.Title);
或者在实体类字段添加属性
[AdaptIgnore]
public string? Title { get; set; }
全局忽略Id
属性
TypeAdapterConfig.GlobalSettings.When((srcType, destType, mapType) => srcType == destType)
.Ignore("Id");
相关网址
分类:
.NET Core
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示