iT邦幫忙

2026 iThome 鐵人賽

DAY 29
0
自我挑戰組

學習C#續系列 第 29 篇

Day 29: 綜合實作專案(二):資料庫串接、LINQ 統計與非同步匯出

  • 分享至 

  • xImage
  •  

觀念重點複習
EF Core 資料存取與實體對應(Data Persistence):

  • 將記憶體記帳模型映射至 SQLite 資料庫,利用 DbContext 管理實體生命週期。
  • 宣告 DbSet 讓 LINQ 查詢能夠轉譯為原生 SQL 執行。
  • 針對 SQLite 數值型別限制,金額儲存可使用 double 避免排序或部分彙總引發相容性例外。

LINQ 分組統計與財務報表(LINQ GroupBy & Aggregate):

  • 分組統計 (GroupBy):依收支類別(Type)分組,快速計算總收入與總支出:group.Sum(x => x.Amount)。
  • 最大/最小統計 (OrderByDescending, First):迅速抓出最高額單筆支出或近期消費模式。
  • 時間篩選 (Where):篩選指定年份、月份的收支區間。

非同步資料匯出(Asynchronous I/O Export):

  • 匯出大量報表檔案時,使用 async / await 搭配 StreamWriter.WriteAsync,避免檔案寫入阻塞控制台主執行緒。
  • 使用 Newtonsoft.Json 的 JsonConvert.SerializeObject 將分析結果或明細結構化匯出為 .json 報表。
  • 支援格式化 .txt 報表輸出,便於使用者直接閱讀。

完整實作範例:財務收支結算表
https://ithelp.ithome.com.tw/upload/images/20261012/20178925x4sKCG6J0T.png

https://ithelp.ithome.com.tw/upload/images/20261012/20178925UqXdsaVewT.png

https://ithelp.ithome.com.tw/upload/images/20261012/20178925c1YLgHVvU6.png

https://ithelp.ithome.com.tw/upload/images/20261012/20178925Q6Vs6tqDyZ.png

https://ithelp.ithome.com.tw/upload/images/20261012/20178925G3By7jnkLJ.png

執行結果:
新增收入
https://ithelp.ithome.com.tw/upload/images/20261012/20178925MbI1iS0P6E.png

新增支出
https://ithelp.ithome.com.tw/upload/images/20261012/20178925c94sTHYtfZ.png

檢視收支統計報表
https://ithelp.ithome.com.tw/upload/images/20261012/20178925turOfHXoMP.png

匯出TXT檔
https://ithelp.ithome.com.tw/upload/images/20261012/20178925WjfL2lESqu.png

https://ithelp.ithome.com.tw/upload/images/20261012/201789251LUK5Iwc2A.png

https://ithelp.ithome.com.tw/upload/images/20261012/20178925rz1Dmc31yn.png

匯出JSON檔
https://ithelp.ithome.com.tw/upload/images/20261012/20178925pDoybTg77H.png

https://ithelp.ithome.com.tw/upload/images/20261012/20178925LVzqOZBvHR.png

https://ithelp.ithome.com.tw/upload/images/20261012/20178925WqVsFzTu6u.png

離開系統
https://ithelp.ithome.com.tw/upload/images/20261012/20178925xTACqIBePA.png


上一篇
Day 28: 綜合實作專案(一):Console 系統架構與選單設計
系列文
學習C#續 共 29 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言