前言
在上一章节我们在后端框架中引入 SQLite-net
ORM 并封装常用方法(SQLiteHelper),今天我们的任务是设计好班级管理相关的表、完善后端班级管理相关接口并对Swagger自定义配置。
![90bbe2546bf0b894377484294aa45c93.png](https://i-blog.csdnimg.cn/blog_migrate/5bad46b5c4b34130a5c1327848366ccd.png)
七天.NET 8 操作 SQLite 入门到实战详细教程
EasySQLite 项目源码地址
GitHub 地址:https://github.com/YSGStudyHards/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文档放到你想要放到的位置。
![7a0ab7116a08fc25db7e5fad41b52249.png](https://i-blog.csdnimg.cn/blog_migrate/d1ceed32453cd5bedf3d3aef03a23387.png)
项目运行:
![a9df1869f1ce9c415d756cdd144983a5.png](https://i-blog.csdnimg.cn/blog_migrate/358d1e50dede979bde9a5fb1c363c9ad.png)
Swagger API调用效果展示
![1986f571d93e6f9c853b15d9e8e2d3b9.png](https://i-blog.csdnimg.cn/blog_migrate/10c6fedd5d3b8d8b9d759f7cfbc4d7df.png)
![c58a564f073bdb11831cf2fa7326519c.png](https://i-blog.csdnimg.cn/blog_migrate/384d98a8c8a8b73f329a627f980a70be.png)
![c66b69b3caf4fd509d854780d5cda3d1.png](https://i-blog.csdnimg.cn/blog_migrate/3be3470a1796e7e2cb12ac8efc239407.png)
Navicat查看SQLite数据库表数据
注意本文我们的数据库和表都是由代码自动创建生成的,也就是在SQLiteAsyncHelper里面。
![5f93f4b20c952b376f5b5cb8e686fcd3.png](https://i-blog.csdnimg.cn/blog_migrate/273c17c8b5ebc8395da9aa88e909618d.png)
创建成功后的数据库:
![966466b18f43bb6a09cba58723e8f911.png](https://i-blog.csdnimg.cn/blog_migrate/a3a3efe82b5a5dbf526a91bff8878332.png)
Navicat查看数据库表数据
![8367d9ce08d53072b8c33a59e8a366a1.png](https://i-blog.csdnimg.cn/blog_migrate/9dc24865b6fe907c46fbbc252b879ba2.png)
![aefca63520e173f3fd75f6e889ac06b6.png](https://i-blog.csdnimg.cn/blog_migrate/d8f056a587afbeaaa4d3f87c2d7585ba.png)
![1cc23c59ef55337f22abb249aedadc2f.png](https://i-blog.csdnimg.cn/blog_migrate/51b1c59b462bd9337706800b4e3b85dc.png)
![a33c0063aad74b694c627e5906ceeb5f.png](https://i-blog.csdnimg.cn/blog_migrate/58d635eda937cea6ed323ad8a0d9ba0f.png)
免费开源的程序员简历模板
了解作者&获取更多学习资料
程序员常用的开发工具软件推荐
加入DotNetGuide技术社区交流群
.NET/.NET Core ORM框架资源汇总
ASP.NET Core开发者学习指南路线图
学习是一个永无止境的过程,你知道的越多,你不知道的也会越多,在有限的时间内坚持每天多学一点,你一定能成为你想要成为的那个人。不积跬步无以至千里,不积小流无以成江河!!!