星期二, 4月 09, 2024

[EFCore] Scaffold-DbContext

在 [EFCore] 在 Console 專案上安裝設定 內使用 Scaffold-DbContext 產生 DbContext 和 Entity 後,使用時發現有些細節想像中有落差,在官方文章 - Entity Framework Core tools reference - Package Manager Console in Visual Studio 內找到 Scaffold-DbContext 參數說明

必要參數

-Connection 和 -Provider 為必要參數,網路上寫法大多是省略參數標示,寫法如下
-- 完整寫法
Scaffold-DbContext 
    -Connection "Server=.;Database=AsventureWorks2022;Trusted_Connection=True;TrustServerCertificate=true" 
    -Provider Microsoft.EntityFrameworkCore.SqlServer
  
-- 常見寫法
Scaffold-DbContext
    "Server=.;Database=AsventureWorks2022;Trusted_Connection=True;TrustServerCertificate=true"
    Microsoft.EntityFrameworkCore.SqlServer

-Tables

指定要建立 Entity 的 Table,重覆使用該參數,必須每次都明確指定 Table,原因在於 DbContext 會被重建,第一次執行 Scaffold-DbContext 建立的 Entity,在第二次執行 Scaffold-DbContext 後,假如沒有明確指定,Entity 雖然存在,但 DbContext 內是沒有的

-NoOnConfiguring 

預設會在 DbContext.OnConfiguring 內產生下列 Code,連線字串會 HardCode 寫在裡面
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
#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 https://go.microsoft.com/fwlink/?LinkId=723263.
        => optionsBuilder.UseSqlServer("連線字串");

實務上慣用語法
Scaffold-DbContext 
	"Server=.;Database=AdventureWorks2022;Trusted_Connection=True;TrustServerCertificate=true" 
	Microsoft.EntityFrameworkCore.SqlServer 
	-ContextDir DbContextDir            // 指定 DbContext 資料夾位置    
	-Context AdventureWork2022DbContext // 指定 DbContext 名稱
	-OutputDir EntityDir                // 指定 Entity 資料夾位置
	-Table Person                       // 指定特定 Table,不指定即建立整個 DB 內 Table 
	-NoPluralize                        // 不要複數化
	-UseDatabaseNames                   // Entity 名稱和 DB 內一樣
	-Force                              // 覆寫現有檔案

以上語法為方便閱讀,都會換行排列,實際在執行是串接在一起的

沒有留言:

張貼留言