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);
            }


        }
}
相关推荐
凤山老林2 小时前
Spring Boot 启动冲刺:耗时剖析、懒加载策略与事件驱动初始化优化
spring boot·后端·python
RobinDevNotes2 小时前
一套代码发布到十几个平台:Cocos入门速览
typescript·c#·游戏开发
朱涛的自习室2 小时前
我给 Gemini 4 和 DeepSeek 搞了套「末位淘汰」,AI 干活会更猛吗?(Day 3)
android·前端·后端
阿松爱学习4 小时前
【Unity开发】监听Scene场景事件
unity·c#
woniu_maggie5 小时前
SAP MDG主数据治理实战:从架构原理到项目实施全解析
后端
xiaoqiMikko5 小时前
Redis 实战(一):内存满了 —— 拒写、淘汰、被系统杀掉,以及删了 key 内存为什么不降(6.2.4 实测)
redis·后端
工程师小爱5 小时前
电芯尺寸合格,不等于电池包尺寸合格
后端
geovindu5 小时前
rust:Memento Pattern(续)
开发语言·后端·设计模式·rust·行为模式·备忘录模
闲云lazycloud6 小时前
第 1 课:Harness 与 Agent 运行时
人工智能·后端