ASP .Net Core: AutoMapper与DTO的使用(自定类型转换)

发布时间 2023-10-10 11:32:12作者: 胸怀丶若谷

建立DTO物件

创建名为Dtos文件夹, 并添加TodoListSelectDto文件

public class TodoListSelectDto
{
    public Guid TodoId { get; set; }

    public string Name { get; set; } = null!;

    public DateTime InsertTime { get; set; }

    public DateTime UpdateTime { get; set; }

    public bool Enable { get; set; }

    public int Orders { get; set; }

    public string InsertEmployeeName { get; set; }

    public string UpdateEmployeeName { get; set; }
}

原生的类型转换

image

其实就是新建一个DTO,并将对应的字段进行赋值。但这样的方式有些繁琐,接下来介绍第二种方案,使用AtuoMapper

AutoMapper

安装AutoMapper

image

在program.cs文件中添加配置

builder.Services.AddAutoMapper(typeof(Program));

配置规则

新建Profiles文件夹,并创建TodoListProfile文件

using AutoMapper;
using Todo.Dtos;
using Todo.Models;

namespace Todo.Profiles;

public class TodoListProfile:Profile
{
    public TodoListProfile()
    {
        CreateMap<TodoList, TodoListSelectDto>();
    }
}

在controller中使用AutoMapper

image

// autoMapper
private readonly IMapper _iMapper;

public TodoController(IMapper iMapper )
{
    _iMapper = iMapper;
}


[HttpGet("UseAutoMapper")]
public IEnumerable<TodoListSelectDto> UseAutoMapper()
{
    var result = _todoContext.TodoLists.Include(a => a.UpdateEmployee)
        .Include(a => a.InsertEmployee);
    
    return _iMapper.Map<IEnumerable<TodoListSelectDto>>(result.ToList());
}

效果展示

image