在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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)