WPF实战项目十二(API篇):配置AutoMapper

1、新建类库WPFProjectShared,在类库下新建文件夹Dtos,新建BaseDto.cs,继承INotifyPropertyChanged,实现通知更新。

cs 复制代码
public class BaseDto : INotifyPropertyChanged
    {
        public int Id { get; set; }

        public event PropertyChangedEventHandler? PropertyChanged;

        /// <summary>
        /// 实现通知更新
        /// </summary>
        /// <param name="propertyName"></param>
        public void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

2、WPFProjectAPI添加引用WPFProjectShared

3、新建待办事项传输实体TodoDto.cs,继承BaseDto.cs

cs 复制代码
/// <summary>
    /// 待办事项传输实体
    /// </summary>
    public class TodoDto : BaseDto
    {
        /// <summary>
        /// 标题
        /// </summary>
        private string title;

        public string Title
        {
            get { return title; }
            set { title = value; OnPropertyChanged(); }
        }

        /// <summary>
        /// 内容
        /// </summary>
        private string content;

        public string Content
        {
            get { return content; }
            set { content = value; OnPropertyChanged(); }
        }

        /// <summary>
        /// 状态
        /// </summary>
        private string status;

        public string Status
        {
            get { return status; }
            set { status = value; OnPropertyChanged(); }
        }

    }

4、在api层引入AutoMapper,并新建文件夹Extensions,新建帮助类AutoMapperProFile.cs,继承ProFile

cs 复制代码
    public class AutoMapperProFile : Profile
    {
        public AutoMapperProFile()
        {
            CreateMap<ToDo, TodoDto>().ReverseMap();
        }
    }

5、在program.cs中注册AutoMapper的服务

cs 复制代码
//注册AutoMapper服务
builder.Services.AddAutoMapper(typeof(AutoMapperProFile));

6、IToDoService.cs修改代码传入ToDoDto,相应的ToDoService.cs的代码也要修改

cs 复制代码
    public interface IToDoService : IBaseService<TodoDto>
    {
        
    }
cs 复制代码
public class ToDoService : IToDoService
    {
        private readonly IUnitOfWork unitOfWork;
        private readonly IMapper mapper;

        public ToDoService(IUnitOfWork unitOfWork, IMapper mapper)
        {
            this.unitOfWork = unitOfWork;
            this.mapper = mapper;
        }

        /// <summary>
        /// 新增待办事项
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ApiResponse> AddEntityAsync(TodoDto model)
        {
            try
            {
                var todo = mapper.Map<ToDo>(model);
                await unitOfWork.GetRepository<ToDo>().InsertAsync(todo);
                if(await unitOfWork.SaveChangesAsync() > 0)
                {
                    return new ApiResponse(true, model);
                }
                else
                {
                    return new ApiResponse(false, "添加数据失败!");
                }
            }
            catch (Exception ex)
            {

                return new ApiResponse(false, ex.Message);
            }
        }
        /// <summary>
        /// 删除待办事项
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ApiResponse> DeleteEntityAsync(int id)
        {
            try
            {
                var repository = unitOfWork.GetRepository<ToDo>();
                var todo = await repository.GetFirstOrDefaultAsync(predicate: t => t.Id.Equals(id));
                repository.Delete(todo);
                if (await unitOfWork.SaveChangesAsync() > 0)
                {
                    return new ApiResponse(true, "删除数据成功!");
                }
                else
                {
                    return new ApiResponse(false, "删除数据失败!");
                }
            }
            catch (Exception ex)
            {

                return new ApiResponse(false, ex.Message);
            }
        }
       /// <summary>
       /// 查询所有数据
       /// </summary>
       /// <returns></returns>
        public async Task<ApiResponse> GetAllAsync()
        {
            try
            {
                var repository = unitOfWork.GetRepository<ToDo>();
                var todo = await repository.GetAllAsync();
                if (todo != null)
                {
                    return new ApiResponse(true, todo);
                }
                else
                {
                    return new ApiResponse(false, "查询数据失败!");
                }
            }
            catch (Exception ex)
            {

                return new ApiResponse(false, ex.Message);
            }
        }

        /// <summary>
        /// 根据Id查询数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ApiResponse> GetSingleAsync(int id)
        {
            try
            {
                var repository = unitOfWork.GetRepository<ToDo>();
                var todo = await repository.GetFirstOrDefaultAsync(predicate: t => t.Id.Equals(id));
                if (todo != null)
                {
                    return new ApiResponse(true, todo);
                }
                else
                {
                    return new ApiResponse(false, $"未查询到Id={id}的数据!");
                }
            }
            catch (Exception ex)
            {

                return new ApiResponse(false, ex.Message);
            }
        }
        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResponse> UpdateEntityAsync(TodoDto model)
        {
            try
            {
                var dbTodo = mapper.Map<ToDo>(model);
                var repository = unitOfWork.GetRepository<ToDo>();
                var todo = await repository.GetFirstOrDefaultAsync(predicate: t => t.Id.Equals(dbTodo.Id));
                if (todo != null)
                {
                    todo.Title = dbTodo.Title;
                    todo.Content = dbTodo.Content;
                    todo.Status = dbTodo.Status;
                    todo.UpdateDate = DateTime.Now;
                    repository.Update(todo);
                    if(await unitOfWork.SaveChangesAsync() > 0)
                    {
                        return new ApiResponse(true, "更新数据成功!");
                    }
                    else
                    {
                        return new ApiResponse(true, "更新数据失败!");
                    }
                }
                else
                {
                    return new ApiResponse(false, $"未查询到Id={model.Id}的数据!");
                }
            }
            catch (Exception ex)
            {

                return new ApiResponse(false, ex.Message);
            }
        }
    }

7、F5运行项目

相关推荐
禁默2 分钟前
【学术会议-第五届机械设计与仿真国际学术会议(MDS 2025) 】前端开发:技术与艺术的完美融合
前端·论文·学术
binnnngo7 分钟前
2.体验vue
前端·javascript·vue.js
LCG元8 分钟前
Vue.js组件开发-实现多个文件附件压缩下载
前端·javascript·vue.js
索然无味io11 分钟前
组件框架漏洞
前端·笔记·学习·安全·web安全·网络安全·前端框架
╰つ゛木槿20 分钟前
深入探索 Vue 3 Markdown 编辑器:高级功能与实现
前端·vue.js·编辑器
yqcoder39 分钟前
Commander 一款命令行自定义命令依赖
前端·javascript·arcgis·node.js
前端Hardy1 小时前
HTML&CSS :下雪了
前端·javascript·css·html·交互
醉の虾1 小时前
VUE3 使用路由守卫函数实现类型服务器端中间件效果
前端·vue.js·中间件
码上飞扬2 小时前
Vue 3 30天精进之旅:Day 05 - 事件处理
前端·javascript·vue.js
火烧屁屁啦2 小时前
【JavaEE进阶】应用分层
java·前端·java-ee