七天.NET 8操作SQLite入門到實戰

2023-12-07 06:00:25

前言

在上一章節我們在後端框架中引入 SQLite-net ORM 並封裝常用方法(SQLiteHelper),今天我們的任務是設計好班級管理相關的表、完善後端班級管理相關介面並對Swagger自定義設定。

七天.NET 8 操作 SQLite 入門到實戰詳細教學

EasySQLite 專案原始碼地址

GitHub 地址:https://github.com/YSGStudyHards/EasySQLite

班級管理相關的表設計

班級表的欄位可以包括:

  1. 班級ID(ClassID):用於唯一標識每個班級[主鍵自增]。
  2. 班級名稱(ClassName):班級的名稱。
  3. 建立時間(CreateTime):班級建立的時間。

班級學生表的欄位可以包括:

  1. 學生ID(StudentID):用於唯一標識每個學生[主鍵自增]。
  2. 班級ID(ClassID):所屬班級的ID,與班級表中的班級ID相關聯。
  3. 姓名(Name):學生的姓名。
  4. 年齡(Age):學生的年齡。
  5. 性別(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執行效果:

Swagger API呼叫效果展示

 

Navicat檢視SQLite表資料

注意本文我們的資料庫和表都是由程式碼自動建立生成的,也就是在SQLiteAsyncHelper裡面。

建立成功後的資料庫:

Navicat檢視資料庫表資料

DotNetGuide技術社群交流群

  • DotNetGuide技術社群是一個面向.NET開發者的開源技術社群,旨在為開發者們提供全面的C#/.NET/.NET Core相關學習資料、技術分享和諮詢、專案推薦、招聘資訊和解決問題的平臺。
  • 在這個社群中,開發者們可以分享自己的技術文章、專案經驗、遇到的疑難技術問題以及解決方案,並且還有機會結識志同道合的開發者。
  • 我們致力於構建一個積極向上、和諧友善的.NET技術交流平臺,為廣大.NET開發者帶來更多的價值和成長機會。

歡迎加入DotNetGuide技術社群微信交流群