auotmapper在net core 3.1的使用

1安装automapper 包 (需要注意的是如果在同一个解决方法的不同项目安装了两个包,会导致冲突报错)

选择   AutoMapper.Extensions.Microsoft.DependencyInjection

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

services.AddAutoMapper(typeof(StartupHelp.MapperProfiles).Assembly);        //StartupHelp.MapperProfiles就是要注册的类型所在程序集

3创建一个类继承Profile

 public class UserProfile : AutoMapper.Profile
    {
        //添加你的实体映射关系.
        public UserProfile()
        {
            //UserInfoEntity转UserInfoDto.
            CreateMap<UserInfoEntity, UserInfoDto>();   //前面是原类型,后面是目标类型
            
        }
    }

然后使用依赖注入(一般在服务层,只要安装一次即可)

public class xxxService : IxxxService
    {
        
        private readonly IMapper _mapper;

        public xxxService(IMapper mapper)
        {
            
            this._mapper = mapper;
        }
    }

然后就可以使用

var entityDtoList = _mapper.Map<List<EntityDto>>(EntityList);   //list结合
var entityDto = _mapper.Map<EntityDto>(Entity); //尖括号里面是要转换的目标类型,原括号是源数据
原文地址:https://www.cnblogs.com/carlpeng/p/13157376.html