asp.net core automapper的使用

1.安装automapper的nuget包
AutoMapper.Extensions.Microsoft.DependencyInjection
2.创建需要映射的类和转换后的类

public class studto
    {
        public int sn { get; set; }
        public string name { get; set; }
        public string sex { get; set; }
        public int age { get; set; }
        public string addre { get; set; }
    }

    public class stu
    {
        public int sn { get; set; }
        public string name { get; set; }
        public string sex { get; set; }
        public int age { get; set; }
        public string address { get; set; }
    }

3.创建映射类需要继承automapper中的profile类

 public class customProfile : Profile
    {
        public customProfile()
        {          
            //如果dto类中的字段和实体类中的字段名相同就不需要配置字段,字段不相同,则要配置
            CreateMap<stu, studto>()
            //stu类映射到studto类上,studto类中的addre,与stu类中的address类对应
            CreateMap<stu, studto>().ForMember(dest => dest.addre, opt => opt.MapFrom(src => src.address));
        }
    }

4.在program中注入automapper服务

builder.Services.AddAutoMapper(typeof(customProfile));
builder.Services.AddScoped<Iservice, service>();

5.准备好实体数据

public interface Iservice
    {
        List<stu> lsstu();
    }
public class service : Iservice
    {
        public List<stu> lsstu()
        {
            List<stu> stus = new List<stu>();
            stus.Add(new stu() { sn = 1, name = "pzx", sex = "nan", age = 10, address = "pzx" });
            stus.Add(new stu() { sn = 2, name = "pzx", sex = "nan", age = 10, address = "pzx" });
            stus.Add(new stu() { sn = 3, name = "pzx", sex = "nan", age = 10, address = "pzx" });
            return stus;
        }
    }

6.在控制中通过构造函数注入的方式调用automapper的map方法,完成实体转换

 [HttpGet]
        public IActionResult Index()
        {
            var ls = iservice.lsstu();
            List<studto> lsdto = new List<studto>();
            foreach (var item in ls)
            {
                var dtols = _mapper.Map<stu, studto>(item);
                lsdto.Add(dtols);
            }
            return new JsonResult(lsdto);
        }

调用效果
asp.net core automapper的使用_第1张图片

你可能感兴趣的:(asp.net,后端)