Asp.Net 6.0 集成 AutoMapper 初入

AutoMapper

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

依赖

NuGet中搜搜AutoMapper进行安装即可

配置

创建Profile,配置实体映射关系
MapperConfigurationExpression 继承自 Profile

public class AutoMapperProFile:MapperConfigurationExpression
    {

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


        }
    }

配置到Asp.Net IOC中


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

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

使用

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


        }
}

你可能感兴趣的:(asp.net,后端,c#)