在 .NET 5 / 6的 Windows Form 中使用 EF Core
現在的.NET 5 / 6,已經可以建立 WindowsForm 專案了,我這邊使用 Visual Studio 2022 以 NET 6 建立一個全新的 WindowsForm 範本,並示範如何在 WindowsForm 中使用 EF Core。若你是使用 Visual Studio 2019 則能建立的最高板本是 .NET 5,兩者的安裝方式相同,可以安心服用。 點選 Visual Studio 右側的方案總管,對方案按右鍵後,點選管理 NuGet 套件 這邊要安裝兩個套件,若是.NET 5,就安裝5.x版本,若是.NET 6,就安裝6.x版本, Microsoft.EntityFrameworkCore.SqlServer Microsoft.EntityFrameworkCore.Tools 補充:若你要使用的資料庫是Sqlite,那就是安裝Microsoft.EntityFrameworkCore.Sqlite,其他資料庫請參考 EF Core 資料庫提供者。Tools這個套件是使用 Visual Studio 產生資料庫模型的工具。 安裝過程中會出現安裝其他相關套件的詢問,都按確定 接著開啟套件管理主控台,輸入以下指令來從資料庫產生來產生資料模型,請以自己的資料庫更改連線字串 Scaffold-DbContext 'Data Source=DANNY-LIU-ASUS;Initial Catalog=TestDB;Integrated Security=True' Microsoft.EntityFrameworkCore.SqlServer 右鍵貼上並執行後,你可以看到在方案總管中多了 TestDBContext 與 User 在TestDBContext可以看到資料庫的連線字串,若想要移除可參考微軟提供的連結 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { #warning #To protect potentially sensitive information in your connection string, you should move it out of source code. #You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration # - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263. optionsBuilder.UseSqlServer("Data Source=DANNY-LIU-ASUS;Initial Catalog=TestDB;Integrated Security=True"); } } 回到 Windows Form 視窗,這邊新增了一個DataGridView,並拖曳進Form1視窗中 ...