ASP .Net Core: AutoMapper与DTO的使用(自定类型转换)
建立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; }
}
原生的类型转换
其实就是新建一个DTO,并将对应的字段进行赋值。但这样的方式有些繁琐,接下来介绍第二种方案,使用AtuoMapper
AutoMapper
安装AutoMapper
在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
// 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());
}
效果展示
学以致用,知行合一