.net core3.1 AutoMapper

chafferer_發表於2020-08-07

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());//
        }

相關文章