前言
在上一章节我们在后端框架中引入 SQLite-net
ORM 并封装常用方法(SQLiteHelper),今天我们的任务是设计好班级管理相关的表、完善后端班级管理相关接口并对Swagger自定义配置。
七天.NET 8 操作 SQLite 入门到实战详细教程
- 第一天 SQLite 简介
- 第二天 在 Windows 上配置 SQLite 环境
- 第三天 SQLite 快速入门
- 第四天 EasySQLite 前后端项目框架搭建
- 第五天引入 SQLite-net ORM 并封装常用方法
EasySQLite 项目源码地址
班级管理相关的表设计
班级表的字段可以包括:
- 班级ID(ClassID):用于唯一标识每个班级[主键自增]。
- 班级名称(ClassName):班级的名称。
- 创建时间(CreateTime):班级创建的时间。
班级学生表的字段可以包括:
- 学生ID(StudentID):用于唯一标识每个学生[主键自增]。
- 班级ID(ClassID):所属班级的ID,与班级表中的班级ID相关联。
- 姓名(Name):学生的姓名。
- 年龄(Age):学生的年龄。
- 性别(Gender):学生的性别。
班级管理相关的表对应模型
SchoolClass
public class SchoolClass { /// <summary> /// 班级ID [主键,自动递增] /// </summary> [PrimaryKey, AutoIncrement] public int ClassID { get; set; } /// <summary> /// 班级名称 /// </summary> public string ClassName { get; set; } /// <summary> /// 创建时间 /// </summary> public DateTime CreateTime { get; set; } }
Student
public class Student { /// <summary> /// 学生ID [主键,自动递增] /// </summary> [PrimaryKey, AutoIncrement] public int StudentID { get; set; } /// <summary> /// 班级ID /// </summary> public int ClassID { get; set; } /// <summary> /// 学生姓名 /// </summary> public string Name { get; set; } /// <summary> /// 学生年龄 /// </summary> public int Age { get; set; } /// <summary> /// 学生性别 /// </summary> public string Gender { get; set; } }
接口统一的响应模型
为了实现统一的响应模型,这里创建一个名为 ApiResponse的泛型类。
public class ApiResponse<T> { /// <summary> /// 是否成功 /// </summary> public bool Success { get; set; } /// <summary> /// 响应消息 /// </summary> public string Message { get; set; } /// <summary> /// 返回的数据 /// </summary> public T Data { get; set; } }
学校班级管理接口代码
/// <summary> /// 学校班级管理 /// </summary> [ApiController] [Route("[controller]")] public class SchoolClassController : ControllerBase { private readonly SQLiteAsyncHelper<SchoolClass> _schoolClassHelper; /// <summary> /// 依赖注入 /// </summary> /// <param name="schoolClassHelper">schoolClassHelper</param> public SchoolClassController(SQLiteAsyncHelper<SchoolClass> schoolClassHelper) { _schoolClassHelper = schoolClassHelper; } /// <summary> /// 班级创建 /// </summary> /// <param name="schoolClass">创建班级信息</param> /// <returns></returns> [HttpPost] public async Task<ApiResponse<int>> CreateClass([FromBody] SchoolClass schoolClass) { try { int insertNumbers = await _schoolClassHelper.InsertAsync(schoolClass); if (insertNumbers > 0) { return new ApiResponse<int> { Success = true, Message = "创建班级成功" }; } else { return new ApiResponse<int> { Success = false, Message = "创建班级失败" }; } } catch (Exception ex) { return new ApiResponse<int> { Success = false, Message = ex.Message }; } } /// <summary> /// 获取所有班级信息 /// </summary> [HttpGet] public async Task<ApiResponse<List<SchoolClass>>> GetClasses() { try { var classes = await _schoolClassHelper.QueryAllAsync().ConfigureAwait(false); return new ApiResponse<List<SchoolClass>> { Success = true, Data = classes }; } catch (Exception ex) { return new ApiResponse<List<SchoolClass>> { Success = false, Message = ex.Message }; } } /// <summary> /// 根据班级ID获取班级信息 /// </summary> /// <param name="classId">班级ID</param> /// <returns></returns> [HttpGet("{classId}")] public async Task<ApiResponse<SchoolClass>> GetClass(int classId) { try { var schoolClass = await _schoolClassHelper.QuerySingleAsync(c => c.ClassID == classId).ConfigureAwait(false); if (schoolClass != null) { return new ApiResponse<SchoolClass> { Success = true, Data = schoolClass }; } else { return new ApiResponse<SchoolClass> { Success = false, Message = "班级不存在" }; } } catch (Exception ex) { return new ApiResponse<SchoolClass> { Success = false, Message = ex.Message }; } } /// <summary> /// 更新班级信息 /// </summary> /// <param name="classId">班级ID</param> /// <param name="updatedClass">更新的班级信息</param> /// <returns></returns> [HttpPut("{classId}")] public async Task<ApiResponse<int>> UpdateClass(int classId, [FromBody] SchoolClass updatedClass) { try { var existingClass = await _schoolClassHelper.QuerySingleAsync(c => c.ClassID == classId).ConfigureAwait(false); if (existingClass != null) { existingClass.ClassName = updatedClass.ClassName; var updateResult = await _schoolClassHelper.UpdateAsync(existingClass).ConfigureAwait(false); if (updateResult > 0) { return new ApiResponse<int> { Success = true, Message = "班级信息更新成功" }; } else { return new ApiResponse<int> { Success = false, Message = "班级信息更新失败" }; } } else { return new ApiResponse<int> { Success = false, Message = "班级不存在" }; } } catch (Exception ex) { return new ApiResponse<int> { Success = false, Message = ex.Message }; } } /// <summary> /// 班级删除 /// </summary> /// <param name="classId">班级ID</param> /// <returns></returns> [HttpDelete("{classId}")] public async Task<ApiResponse<int>> DeleteClass(int classId) { try { var deleteResult = await _schoolClassHelper.DeleteAsync(classId).ConfigureAwait(false); if (deleteResult > 0) { return new ApiResponse<int> { Success = true, Message = "班级删除成功" }; } else { return new ApiResponse<int> { Success = true, Message = "班级删除失败" }; } } catch (Exception ex) { return new ApiResponse<int> { Success = false, Message = ex.Message }; } } }
学生管理接口代码
/// <summary> /// 学生管理 /// </summary> [ApiController] [Route("[controller]")] public class StudentController : ControllerBase { private readonly SQLiteAsyncHelper<Student> _studentHelper; /// <summary> /// 依赖注入 /// </summary> /// <param name="studentHelper">studentHelper</param> public StudentController(SQLiteAsyncHelper<Student> studentHelper) { _studentHelper = studentHelper; } /// <summary> /// 创建新的学生记录 /// </summary> /// <param name="student">添加的学生信息</param> /// <returns></returns> [HttpPost] public async Task<ApiResponse<int>> CreateAsync([FromBody] Student student) { var response = new ApiResponse<int>(); try { var insertNumbers = await _studentHelper.InsertAsync(student).ConfigureAwait(false); if (insertNumbers > 0) { response.Success = true; response.Message = "添加成功"; } else { response.Success = false; response.Message = "插入失败"; } } catch (Exception ex) { response.Success = false; response.Message = ex.Message; } return response; } /// <summary> /// 查询所有学生记录 /// </summary> /// <returns></returns> [HttpGet] public async Task<ApiResponse<List<Student>>> GetAllAsync() { var response = new ApiResponse<List<Student>>(); try { var students = await _studentHelper.QueryAllAsync().ConfigureAwait(false); response.Success = true; response.Data = students; } catch (Exception ex) { response.Success = false; response.Message = ex.Message; } return response; } /// <summary> /// 根据学生ID查询学生信息 /// </summary> /// <param name="studentID">学生ID</param> /// <returns></returns> [HttpGet("{studentID}")] public async Task<ApiResponse<Student>> GetByIdAsync(int studentID) { var response = new ApiResponse<Student>(); try { var student = await _studentHelper.QuerySingleAsync(x => x.StudentID == studentID).ConfigureAwait(false); if (student != null) { response.Success = true; response.Data = student; } else { response.Success = false; response.Message = "未找到学生信息"; } } catch (Exception ex) { response.Success = false; response.Message = ex.Message; } return response; } /// <summary> /// 更新学生记录 /// </summary> /// <param name="studentID">学生ID</param> /// <param name="editstudent">更新的学生信息</param> /// <returns></returns> [HttpPut("{studentID}")] public async Task<ApiResponse<int>> UpdateAsync(int studentID, [FromBody] Student editstudent) { var response = new ApiResponse<int>(); try { var student = await _studentHelper.QuerySingleAsync(x => x.StudentID == studentID).ConfigureAwait(false); if (student != null) { student.Age = editstudent.Age; student.Name = editstudent.Name; student.Gender = editstudent.Gender; student.ClassID = editstudent.ClassID; int updateResult = await _studentHelper.UpdateAsync(student).ConfigureAwait(false); if (updateResult > 0) { response.Success = true; response.Message = "学生信息更新成功"; } else { response.Success = false; response.Message = "学生信息更新失败"; } } else { response.Success = false; response.Message = "未找到学生信息"; } } catch (Exception ex) { response.Success = false; response.Message = ex.Message; } return response; } /// <summary> /// 删除学生记录 /// </summary> /// <param name="studentID">学生ID</param> /// <returns></returns> [HttpDelete("{studentID}")] public async Task<ApiResponse<int>> DeleteAsync(int studentID) { var response = new ApiResponse<int>(); try { int deleteResult = await _studentHelper.DeleteAsync(studentID).ConfigureAwait(false); if (deleteResult > 0) { response.Success = true; response.Message = "删除成功"; } else { response.Success = false; response.Message = "未找到学生信息"; } } catch (Exception ex) { response.Success = false; response.Message = ex.Message; } return response; } }
对应服务注册
在Program.cs
类中:
// 注册服务 builder.Services.AddScoped<SQLiteAsyncHelper<SchoolClass>>(); builder.Services.AddScoped<SQLiteAsyncHelper<Student>>();
Swagger自定义和扩展
Swagger 提供了为对象模型进行归档和自定义 UI 以匹配你的主题的选项。
传递给 AddSwaggerGen 方法的配置操作会添加诸如作者、许可证和说明的信息。在 Program.cs
中添加如下Swagger自定义配置:
// 添加Swagger服务 builder.Services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new OpenApiInfo { Title = "EasySQLite API", Version = "V1", Description = ".NET 8操作SQLite入门到实战", Contact = new OpenApiContact { Name = "GitHub源码地址", Url = new Uri("https://github.com/YSGStudyHards/EasySQLite") } }); // 获取xml文件名 var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; // 获取xml文件路径 var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); // 添加控制器层注释,true表示显示控制器注释 options.IncludeXmlComments(xmlPath, true); // 对action的名称进行排序,如果有多个,就可以看见效果了 options.OrderActionsBy(o => o.RelativePath); });
项目右键,选择属性,找到生成下面的输出选中生成包含API文档的文件,如下图所示:
注意:关于XML文档文件路径是需要你先勾选上面生成包含API文档的文件的时候运行项目才会生成该项目的XML文档,然后可以把生成的XML文档放到你想要放到的位置。
项目运行:
Swagger API调用效果展示
Navicat查看SQLite数据库表数据
注意本文我们的数据库和表都是由代码自动创建生成的,也就是在SQLiteAsyncHelper里面。
创建成功后的数据库:
Navicat查看数据库表数据