在Asp.Net Core中使用AutoMapper进行对象映射

在Asp.Net Core中使用AutoMapper进行对象映射

怎样高效便捷的处理对象映射呢,我们可以使用AutoMapper来进行实体类到Dto

13.0以上的版本中,只需要安装AutoMapper包,在这之下的版本中还需要安装AutoMapper.Extensions.Microsoft.DependencyIn包。

1.添加一个profile,他需要继承Profile类,在构造函数中创建映射:

public class Mapperfile:Profile
{
    public Mapperfile()
    {
        CreateMap<SparepartsStoragelocation, SparepartsStoragelocationDTO>();
    }
}

2.在program.cs文件中添加配置如下:

services.AddAutoMapper(cfg => {
    cfg.AddProfile<Mapperfile>();
});

3.在你需要他的地方注入他:

public class TestController{
    private readonly IMapper _mapper;
	public SparepartsStoragelocationController( IMapper mapper)
	{
   	 	_mapper = mapper;
	}
    public Method(){
        List<Dto> list = _mapper.Map<List<entity>, List<Dto>>(_data);
    }
}
public class entity
{
    public int ID { get; set; }
    public DateTime? CreateTime { get; set; }
    public string? Code { get; set; }
    public string? CreatePeople { get; set; }
    public bool? IsDelete { get; set; }
}
public record Dto(int ID,string Code,string CreatePeople, DateTime CreateTime);

你可以看到,我创建的映射是对象,而方法类内实际映射的是List集合,你只需要这么做即可

AutoMapper还支持这些:

  • IEnumerable
  • IEnumerable<T>
  • ICollection
  • ICollection<T>
  • IList
  • IList<T>
  • List<T>
  • Arrays
posted @   ssz0312  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示