Asp.Net 6.0 集成 AutoMapper 初入

AutoMapper

在后端开发中,对外接口时通常使用的实体是DTO,用于数据传输使用。在DTO到数据访问层的时候,需要进行DTO实体到DAO实体类的转换。这时,我们使用AutoMapper可以简化这个转换对象的过程。

依赖

NuGet中搜搜AutoMapper进行安装即可

配置

创建Profile,配置实体映射关系

MapperConfigurationExpression 继承自 Profile

cs 复制代码
public class AutoMapperProFile:MapperConfigurationExpression
    {

        public AutoMapperProFile()
        {
            // 增加实体间的转换
            CreateMap<ToDo, ToDoDto>().ReverseMap();
            CreateMap<Memo, MemoDto>().ReverseMap();
            CreateMap<User, UserDto>().ReverseMap();
            
            /**
             *  使用 ForMember 对映射规则做进一步的加工,可以使用自定义转换器
            CreateMap<PostModel, PostViewModel>()
            .ForMember(destination => destination.CommentCounts, source => source.MapFrom(i => i.Comments.Count()));
            **/


        }
    }

配置到Asp.Net IOC中

cs 复制代码
#region 注册AutoMapper
var autoMapperConfiguration = new MapperConfiguration(config =>
{
    config.AddProfile(new AutoMapperProFile());
});

builder.Services.AddSingleton(autoMapperConfiguration.CreateMapper());
#endregion

使用

cs 复制代码
public class ToDoService : IToDoService
    {

        public IUnitOfWork Uow { get; }
        public ILogger<ToDoService> Logger { get; }
        public IMapper Mapper { get; }

        public ToDoService(IUnitOfWork uow, ILogger<ToDoService> logger,IMapper mapper)
        {
            Uow = uow;
            Logger = logger;
            Mapper = mapper;
        }
		
		public async Task<ApiResponse> AddAsync(ToDoDto model)
        {
            try
            {
                // AutoMapper 转换
                // var items = Mapper.Map<IList<ToDoDto>>(toDos.Items);
                var Todo = Mapper.Map<ToDo>(model);
                IRepository<ToDo> repository = Uow.GetRepository<ToDo>();
                await repository.InsertAsync(Todo);
                if (await Uow.SaveChangesAsync() > 0)
                {
                    return new ApiResponse(true, Todo);
                }
                return new ApiResponse("添加数据失败");
            }
            catch (Exception ex)
            {
                return new ApiResponse(ex.Message);
            }


        }
}
相关推荐
掘金者阿豪16 分钟前
上线前能跑,上线后挂了,三个隐性的SQL陷阱
后端
鱼听禅24 分钟前
C#学习笔记-Entity Framework Core基础操作学习
c#·orm·ef core
用户83562907805127 分钟前
如何使用 Python 为 PDF 添加和管理图层
后端·python
SimonKing42 分钟前
那个号称"对标 Spring"的国产框架 Solon,到底行不行?
java·后端·程序员
霸道流氓气质1 小时前
SpringBoot中使用字典驱动的动态路由示例
java·spring boot·后端
用户69371750013841 小时前
Kimi K3 综合能力处于全球第一梯队
android·前端·后端
Z5998178411 小时前
c#软件开发学习笔记--分组、游标与临时表、分页
笔记·学习·c#
anno1 小时前
Agent 新手 Skill 优先级指南:从第一套必装工作流,到专业能力补全
前端·后端
anno2 小时前
别再把文档“一刀切”:用 LangChain.js 做好 RAG 的第一公里
前端·后端
用户713874229002 小时前
claude_rules 深度解析:Claude Code 的模块化路径作用域规则
后端