C# 实体转换 AutoMapper


//首先 安装 AutoMapper,然后在应用程序启动时配置AutoMapper以了解要映射的类型:

var config = new MapperConfiguration(cfg => { cfg.CreateMap(); });

//然后在您的应用程序代码中,执行映射:
IMapper iMapper = config.CreateMapper();
var classifyResult = iMapper.Map<源实体Entity,目标Entity>(item);

1.NuGet安装AutoMapper.Extensions.Microsoft.DependencyInjection

2.创建配置文件,并添加映射配置
需要继承AutoMapper中的Profile

public class AutoMapperProfiles : Profile
{
    public AutoMapperProfiles()
    {
        //构造函数中创建映射关系
        CreateMap();
    }
}

3.在Startup启动类中的ConfigureServices方法中将服务添加到容器

AutoMapperProfiles是上面步骤中定义的配置文件

services.AddAutoMapper(typeof(AutoMapperProfiles));

4.在当前要使用的地方,构造函数引入一下(IMapper)
5.Mapper.Map<你想要转换成的数据>(数据源);

参照:https://blog.csdn.net/sinat_16998945/article/details/103072259