前言
在上一章節(jié)我們?cè)诤蠖丝蚣苤幸?nbsp;SQLite-net
ORM 并封裝常用方法(SQLiteHelper),今天我們的任務(wù)是設(shè)計(jì)好班級(jí)管理相關(guān)的表、完善后端班級(jí)管理相關(guān)接口并對(duì)Swagger自定義配置。
EasySQLite 項(xiàng)目源碼地址
班級(jí)管理相關(guān)的表設(shè)計(jì)
班級(jí)表的字段可以包括:
- 班級(jí)ID(ClassID):用于唯一標(biāo)識(shí)每個(gè)班級(jí)[主鍵自增]。
- 班級(jí)名稱(ClassName):班級(jí)的名稱。
- 創(chuàng)建時(shí)間(CreateTime):班級(jí)創(chuàng)建的時(shí)間。
班級(jí)學(xué)生表的字段可以包括:
- 學(xué)生ID(StudentID):用于唯一標(biāo)識(shí)每個(gè)學(xué)生[主鍵自增]。
- 班級(jí)ID(ClassID):所屬班級(jí)的ID,與班級(jí)表中的班級(jí)ID相關(guān)聯(lián)。
班級(jí)管理相關(guān)的表對(duì)應(yīng)模型
SchoolClass
public class SchoolClass
{
/// <summary>
/// 班級(jí)ID [主鍵,自動(dòng)遞增]
/// </summary>
[PrimaryKey, AutoIncrement]
public int ClassID { get; set; }
/// <summary>
/// 班級(jí)名稱
/// </summary>
public string ClassName { get; set; }
/// <summary>
/// 創(chuàng)建時(shí)間
/// </summary>
public DateTime CreateTime { get; set; }
}
Student
public class Student
{
/// <summary>
/// 學(xué)生ID [主鍵,自動(dòng)遞增]
/// </summary>
[PrimaryKey, AutoIncrement]
public int StudentID { get; set; }
/// <summary>
/// 班級(jí)ID
/// </summary>
public int ClassID { get; set; }
/// <summary>
/// 學(xué)生姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 學(xué)生年齡
/// </summary>
public int Age { get; set; }
/// <summary>
/// 學(xué)生性別
/// </summary>
public string Gender { get; set; }
}
接口統(tǒng)一的響應(yīng)模型
為了實(shí)現(xiàn)統(tǒng)一的響應(yīng)模型,這里創(chuàng)建一個(gè)名為 ApiResponse的泛型類。
public class ApiResponse<T>
{
/// <summary>
/// 是否成功
/// </summary>
public bool Success { get; set; }
/// <summary>
/// 響應(yīng)消息
/// </summary>
public string Message { get; set; }
/// <summary>
/// 返回的數(shù)據(jù)
/// </summary>
public T Data { get; set; }
}
學(xué)校班級(jí)管理接口代碼
/// <summary>
/// 學(xué)校班級(jí)管理
/// </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>
/// 班級(jí)創(chuàng)建
/// </summary>
/// <param name="schoolClass">創(chuàng)建班級(jí)信息</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 = "創(chuàng)建班級(jí)成功"
};
}
else
{
return new ApiResponse<int>
{
Success = false,
Message = "創(chuàng)建班級(jí)失敗"
};
}
}
catch (Exception ex)
{
return new ApiResponse<int>
{
Success = false,
Message = ex.Message
};
}
}
/// <summary>
/// 獲取所有班級(jí)信息
/// </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>
/// 根據(jù)班級(jí)ID獲取班級(jí)信息
/// </summary>
/// <param name="classId">班級(jí)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 = "班級(jí)不存在"
};
}
}
catch (Exception ex)
{
return new ApiResponse<SchoolClass>
{
Success = false,
Message = ex.Message
};
}
}
/// <summary>
/// 更新班級(jí)信息
/// </summary>
/// <param name="classId">班級(jí)ID</param>
/// <param name="updatedClass">更新的班級(jí)信息</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 = "班級(jí)信息更新成功"
};
}
else
{
return new ApiResponse<int>
{
Success = false,
Message = "班級(jí)信息更新失敗"
};
}
}
else
{
return new ApiResponse<int>
{
Success = false,
Message = "班級(jí)不存在"
};
}
}
catch (Exception ex)
{
return new ApiResponse<int>
{
Success = false,
Message = ex.Message
};
}
}
/// <summary>
/// 班級(jí)刪除
/// </summary>
/// <param name="classId">班級(jí)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 = "班級(jí)刪除成功"
};
}
else
{
return new ApiResponse<int>
{
Success = true,
Message = "班級(jí)刪除失敗"
};
}
}
catch (Exception ex)
{
return new ApiResponse<int>
{
Success = false,
Message = ex.Message
};
}
}
}
學(xué)生管理接口代碼
/// <summary>
/// 學(xué)生管理
/// </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>
/// 創(chuàng)建新的學(xué)生記錄
/// </summary>
/// <param name="student">添加的學(xué)生信息</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>
/// 查詢所有學(xué)生記錄
/// </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>
/// 根據(jù)學(xué)生ID查詢學(xué)生信息
/// </summary>
/// <param name="studentID">學(xué)生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 = "未找到學(xué)生信息";
}
}
catch (Exception ex)
{
response.Success = false;
response.Message = ex.Message;
}
return response;
}
/// <summary>
/// 更新學(xué)生記錄
/// </summary>
/// <param name="studentID">學(xué)生ID</param>
/// <param name="editstudent">更新的學(xué)生信息</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 = "學(xué)生信息更新成功";
}
else
{
response.Success = false;
response.Message = "學(xué)生信息更新失敗";
}
}
else
{
response.Success = false;
response.Message = "未找到學(xué)生信息";
}
}
catch (Exception ex)
{
response.Success = false;
response.Message = ex.Message;
}
return response;
}
/// <summary>
/// 刪除學(xué)生記錄
/// </summary>
/// <param name="studentID">學(xué)生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 = "未找到學(xué)生信息";
}
}
catch (Exception ex)
{
response.Success = false;
response.Message = ex.Message;
}
return response;
}
}
對(duì)應(yīng)服務(wù)注冊(cè)
在Program.cs
類中:
// 注冊(cè)服務(wù)
builder.Services.AddScoped<SQLiteAsyncHelper<SchoolClass>>();
builder.Services.AddScoped<SQLiteAsyncHelper<Student>>();
Swagger自定義和擴(kuò)展
Swagger 提供了為對(duì)象模型進(jìn)行歸檔和自定義 UI 以匹配你的主題的選項(xiàng)。
傳遞給 AddSwaggerGen 方法的配置操作會(huì)添加諸如作者、許可證和說(shuō)明的信息。在 Program.cs
中添加如下Swagger自定義配置:
// 添加Swagger服務(wù)
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "EasySQLite API",
Version = "V1",
Description = ".NET 8操作SQLite入門(mén)到實(shí)戰(zhàn)",
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);
// 對(duì)action的名稱進(jìn)行排序,如果有多個(gè),就可以看見(jiàn)效果了
options.OrderActionsBy(o => o.RelativePath);
});
項(xiàng)目右鍵,選擇屬性,找到生成下面的輸出選中生成包含API文檔的文件,如下圖所示:
注意:關(guān)于XML文檔文件路徑是需要你先勾選上面生成包含API文檔的文件的時(shí)候運(yùn)行項(xiàng)目才會(huì)生成該項(xiàng)目的XML文檔,然后可以把生成的XML文檔放到你想要放到的位置。
項(xiàng)目運(yùn)行:
Swagger API調(diào)用效果展示
Navicat查看SQLite數(shù)據(jù)庫(kù)表數(shù)據(jù)
注意本文我們的數(shù)據(jù)庫(kù)和表都是由代碼自動(dòng)創(chuàng)建生成的,也就是在SQLiteAsyncHelper里面。
創(chuàng)建成功后的數(shù)據(jù)庫(kù):
Navicat查看數(shù)據(jù)庫(kù)表數(shù)據(jù)