WPF实战项目十一(API篇):待办事项功能api接口

1、新建ToDoController.cs继承基础控制器BaseApiController,但是一般业务代码不写在控制器内,业务代码写在Service,先新建统一返回值格式ApiResponse.cs:

cs 复制代码
public class ApiResponse
    {
        public ApiResponse(bool status, string messages = "")
        {
            this.Message = messages;
            this.Status = status;
        }
        public ApiResponse(bool status, object result)
        {
            this.Status = status;
            this.Result = result;
        }
        /// <summary>
        /// 后台消息
        /// </summary>
        public string Message { get; set; }
        /// <summary>
        /// 返回状态
        /// </summary>
        public bool Status { get; set; }
        /// <summary>
        /// 返回结果
        /// </summary>
        public object Result { get; set; }
    }

2、新建基础Service接口:IBaseService.cs,包含CRUD方法:

cs 复制代码
public interface IBaseService<T>
    {
        Task<ApiResponse> GetAllAsync();
        Task<ApiResponse> GetSingleAsync(int id);
        Task<ApiResponse> AddEntityAsync(T model);
        Task<ApiResponse> UpdateEntityAsync(T model);
        Task<ApiResponse> DeleteEntityAsync(int id);
    }

3、新建待办事项接口IToDoService.cs,继承IBaseService

cs 复制代码
public interface IToDoService : IBaseService<ToDo>
    {
        
    }

4、新建实现类ToDoService.cs,继承IToDoService.cs

cs 复制代码
public class ToDoService : IToDoService
    {
        private readonly IUnitOfWork unitOfWork;

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

        /// <summary>
        /// 新增待办事项
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ApiResponse> AddEntityAsync(ToDo model)
        {
            try
            {
                await unitOfWork.GetRepository<ToDo>().InsertAsync(model);
                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(ToDo model)
        {
            try
            {
                var repository = unitOfWork.GetRepository<ToDo>();
                var todo = await repository.GetFirstOrDefaultAsync(predicate: t => t.Id.Equals(model.Id));
                if (todo != null)
                {
                    todo.Title = model.Title;
                    todo.Content = model.Content;
                    todo.Status = model.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);
            }
        }
    }

5、program.cs里面注入服务

cs 复制代码
builder.Services.AddTransient<IToDoService, ToDoService>();

6、ToDoController.cs里面依赖注入IUnitOfWork和IToDoService,并添加CURD的代码

cs 复制代码
public class ToDoController : BaseApiController
    {
        private readonly IUnitOfWork unitOfWork;
        private readonly IToDoService toDoService;

        public ToDoController(IUnitOfWork unitOfWork, IToDoService toDoService)
        {
            this.unitOfWork = unitOfWork;
            this.toDoService = toDoService;
        }

        [HttpGet]
        public async Task<ApiResponse> GetToDoById(int Id)
        {
            return await toDoService.GetSingleAsync(Id);

        }
        [HttpGet]
        public async Task<ApiResponse> GetAllToDo()
        {
            return await toDoService.GetAllAsync();
        }

        [HttpPost]
        public async Task<ApiResponse> AddToDo([FromBody] ToDo toDo)
        {
            return await toDoService.AddEntityAsync(toDo);
        }

        [HttpDelete]
        public async Task<ApiResponse> DeleteToDo(int id)
        {
            return await toDoService.DeleteEntityAsync(id);
        }

        [HttpPost]
        public async Task<ApiResponse> UpdateToDo(ToDo toDo)
        {
            return await toDoService.UpdateEntityAsync(toDo);
        }
    }

7、F5运行项目

相关推荐
玉面小君1 小时前
从 WPF 到 Avalonia 的迁移系列实战篇6:Trigger、MultiTrigger、DataTrigger 的迁移
wpf·avalonia
招风的黑耳1 天前
Java生态圈核心组件深度解析:Spring技术栈与分布式系统实战
java·spring·wpf
lfw20191 天前
WPF 数据绑定模式详解(TwoWay、OneWay、OneTime、OneWayToSource、Default)
wpf
Magnum Lehar1 天前
3d wpf游戏引擎的导入文件功能c++的.h实现
3d·游戏引擎·wpf
csdn_aspnet1 天前
MongoDB C# .NetCore 驱动程序 序列化忽略属性
mongodb·c#·.netcore
FuckPatience2 天前
WPF Telerik.Windows.Controls.Data.PropertyGrid 自定义属性编辑器
wpf
almighty272 天前
C#WPF控制USB摄像头参数:曝光、白平衡等高级设置完全指南
开发语言·c#·wpf·usb相机·参数设置
军训猫猫头2 天前
12.NModbus4在C#上的部署与使用 C#例子 WPF例子
开发语言·c#·wpf
我要打打代码2 天前
在WPF项目中使用阿里图标库iconfont
wpf
Tiger_shl2 天前
【.Net技术栈梳理】08-控制反转(IoC)与依赖注入(DI)
开发语言·.net·.netcore