在实际的项目开发过程中,我们使用各种ORM框架可以使我们快捷的获取到数据,并且可以将获取到的数据绑定到对应的List<T>中,然后页面或者接口直接显示List<T>中的数据。但是我们最终想要显示在视图或者接口中的数据和数据库实体之间可能存在着差异,一般的做法就是去创建一些对应的“模型”类,然后对获取到的数据再次进行处理,从而满足需求。
因此,如果便捷的实现数据库持久化对象与模型对象之间的实体映射,避免在去代码中手工实现这一过程,就可以大大降低开发的工作量。AutoMapper就是可以帮助我们实现实体转换过程的工具。
AutoMapper是一个OOM(Object-Object-Mapping)组件,从它的英文名字中可以看出,AutoMapper主要是为了实现实体间的相互转换,从而避免我们每次采用手工的方式进行转换。在没有OOM这类组件之前,如果我们需要实现实体之间的转换,只能使用手工修改代码,然后逐个赋值的方式实现映射,而有了OOM组件,可以很方便的帮助我们实现这一需求。看下面的一个例子。
首先创建一个ASP.NET Core WebApi项目:
添加一个Student实体类:
namespace AutoMapperDemo.Model
{
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}
}
添加StudentDTO类,跟Student属性一致。
然后添加一个类,模拟一些测试数据:
using AutoMapperDemo.Model;using System.Collections.Generic;
namespace AutoMapperDemo
{
public class Data
{
public static List<Student> ListStudent { get; set; }
public static List<Student> GetList()
{
ListStudent = new List<Student>();
for (int i = 0; i < 3; i++)
{
Student student = new Student()
{
ID=i,
Name=$"测试_{i}",
Age=20,
Gender="男"
};
ListStudent.Add(student);
}
return ListStudent;
}
}
}
添加Student控制器,通过Get方法获取所有的值:
using System.Collections.Generic;using System.Threading.Tasks;using AutoMapperDemo.Model;using Microsoft.AspNetCore.Mvc;
namespace AutoMapperDemo.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class StudentController : ControllerBase
{
[HttpGet]
public async Task<List<Student>> Get()
{
List<Student> list = new List<Student>();
list = await Task.Run<List<Student>>(() =>
{
return Data.GetList();
});
return list;
}
}
}
Copyright © 2004-2024 Ynicp.com 版权所有 法律顾问:建纬(昆明)律师事务所 昆明市网翼通科技有限公司 滇ICP备08002592号-4