在 .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 套件
file

這邊要安裝兩個套件,若是.NET 5,就安裝5.x版本,若是.NET 6,就安裝6.x版本,

  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFrameworkCore.Tools
    file

補充:若你要使用的資料庫是Sqlite,那就是安裝Microsoft.EntityFrameworkCore.Sqlite,其他資料庫請參考 EF Core 資料庫提供者。Tools這個套件是使用 Visual Studio 產生資料庫模型的工具。

安裝過程中會出現安裝其他相關套件的詢問,都按確定
file

接著開啟套件管理主控台,輸入以下指令來從資料庫產生來產生資料模型,請以自己的資料庫更改連線字串

Scaffold-DbContext 'Data Source=DANNY-LIU-ASUS;Initial Catalog=TestDB;Integrated Security=True' Microsoft.EntityFrameworkCore.SqlServer

file

右鍵貼上並執行後,你可以看到在方案總管中多了 TestDBContextUser

file
file

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視窗中

file

此時按F5執行,應可以編譯成功並運行,可以看到我們的WinForm畫面長這樣

file

回到 Visual Studio,在 Form1 視窗的空白處滑鼠點擊兩下,移動到程式碼,我們要使用 EF Core 產生的 TestDBContext 來取得資料庫中的資料,我想要在 dataGridView1 中顯示資料庫內的 User 資料

public partial class Form1 : Form
{
    private readonly TestDBContext _db = new TestDBContext();

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        var users = _db.Users.ToList();
        dataGridView1.DataSource = users;
    }
}

按F5再重新執行一次,應該就可以看到資料了

file

延伸閱讀:
在 .NET 6 中使用 ADO.NET 實體資料模型 — 以 Windows Form 為例

Facebook留言板