在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 @ 2024-05-12 11:22  ssz0312  阅读(39)  评论(0)    收藏  举报