关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

ASP.NET Core使用AutoMapper

发布时间:2020-08-07 18:37:16

一、前言

在实际的项目开发过程中,我们使用各种ORM框架可以使我们快捷的获取到数据,并且可以将获取到的数据绑定到对应的List<T>中,然后页面或者接口直接显示List<T>中的数据。但是我们最终想要显示在视图或者接口中的数据和数据库实体之间可能存在着差异,一般的做法就是去创建一些对应的模型类,然后对获取到的数据再次进行处理,从而满足需求。

因此,如果便捷的实现数据库持久化对象与模型对象之间的实体映射,避免在去代码中手工实现这一过程,就可以大大降低开发的工作量。AutoMapper就是可以帮助我们实现实体转换过程的工具。

二、使用AutoMapper实现实体映射

AutoMapper是一个OOMObject-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;

        }

    }

}



/template/Home/Zkeys/PC/Static