ASP.NET Core 3.1使用 AutoMapper

多层架构中存在多种模型,如视图模型ViewModel,数据传输对你DTO,ORM对象等,这些数据在层与层之间进行传输必须涉及类型之间的转换。

AutoMapper是一个对象-对象映射器,作用是通过设置好的映射规则把一个对象转化为另一个对象,避免每次都去手动写转换代码。

AutoMapper仅是其中一种方式,现在类似的组件多的多,简单点的自己也可以写,用顺手了哪家都OK。

使用:

1、Nuget引用:

 2、ConfigureServices中进行服务注册(程序集方式):

//添加AutoMapper
services.AddAutoMapper(typeof(StartupHelp.MapperProfiles).Assembly);

3、配置映射规则:

public class MapperProfiles : AutoMapper.Profile
    {
        public MapperProfiles()
        {
            CreateMap<Manager, ManagerModel>().ReverseMap();
        }
    }

4、使用:

public class ManagerService : IManagerService
    {
        private readonly IManagerRepository _repository;
        private readonly IMapper _mapper;

        public ManagerService(IManagerRepository repository, IMapper mapper)
        {
            this._repository = repository;
            this._mapper = mapper;
        }

        public async Task<ManagerModel> GetManagerAsync(string username)
        {
            var obj = await _repository.GetManager(username);
            return _mapper.Map<ManagerModel>(obj);
        }
    }

这里用到了构造函数注入,_mapper.Map<ManagerModel>(obj); 一句话即可实现对象之间的转换。

官方Github地址:https://github.com/AutoMapper/AutoMapper

官方文档(英文):https://automapper.readthedocs.io/en/latest/Getting-started.html

转载地址 https://www.cnblogs.com/quluqi/p/12719643.html

原文地址:https://www.cnblogs.com/netlock/p/13359173.html