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");

相关网址

posted @ 2023-03-14 11:21  雨水的命运  阅读(1033)  评论(0编辑  收藏  举报