1.添加nuget包
AutoMapper.Extensions.Microsoft.DependencyInjection
2.startup.cs
using AutoMapper;
using System;
//...
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
3.新建文件夹Profile(配置映射),新建studentprofile.cs
public class studentprofile:Profile//继承Automapper的Profile{public studentprofile(){CreateMap<Student, studentdto>().ForMember(dest=>dest.xingbie//目标属性名xingbie, opt=>opt.MapFrom(a=>a.sex));//远属性名sex}}
实体类试例
[Table("Student")]public class Student{[Key]public int sid { get; set; }public int sex { get; set; }public int cid { get; set; }}//...
public class studentdto{public int sid { get; set; }public int xingbie { get; set; }}
4.Controllers
private readonly Istudent _stu;private readonly IMapper _map;public TestController(Istudent istudent,IMapper map){_stu = istudent;_map = map;}[HttpGet]public List<studentdto> Get(){return _map.Map<List<studentdto>>(_stu.find());//}