.Net Core 中使用AutoMapper进行对象映射
在.NET CORE中,我们可以使用AutoMapper来实现对象数据传输也就是Dto。
1、需要安装如下两个包,通过Nuget安装即可:
1 AutoMapper
2 AutoMapper.Extensions.Microsoft.DependencyInjection
2、在Startup中添加AutoMapper:
services.AddAutoMapper();
3、创建AutoMapper映射规则,得告诉AutoMapper映射关系:
public class HosTesterProfile : AutoMapper.Profile { public HosTesterProfile() { CreateMap<HosTester, HosTesterHis>().ForMember(x => x.Id, opt => opt.Ignore()) .ForMember(x => x.IsActive, opt => opt.MapFrom(src => true)) .ForMember(x => x.Name, opt => opt.MapFrom(src => src.BranchName)) .ForMember(x => x.Code, opt => opt.MapFrom(src => src.CjdBranceCode)) .ForMember(x => x.OutCode1, opt => opt.MapFrom(src => src.Id)) .ForMember(x => x.OutCode2, opt => opt.MapFrom(src => src.BranchCode)); } }
4、在你的Controller构造函数中注入你的IMapper:
public class SyncTesterToTesterHis { private readonly IMapper _mapper; public SyncTesterToTesterHis( IMapper mapper) { _mapper = mapper; } }
5、单个对象转Dto:
private Task Sync() { var hosTester=new HosTester(){ Id=1,Name="张三" } var hostesterHis = _mapper.Map<HosTesterHis>(hosTester);
}
6、集合转Dto集合:
private Task Sync() { var hosTester=new List<HosTester> { new HosTester(){Id=1,Name="张三"} new HosTester(){Id=2,Name="李四"} } var hostesterHis = _mapper.Map<List<HosTesterHis>>(hosTester); }