Entity Framework Core Migrations
Rider 與 VS 皆可用的 PowerShell 的 migrations 指令筆記
migrations add
結論:(以下為同一行) dotnet-ef migrations add 'Initial' -s .\src\MyProject.HttpApi.Host -p .\src\MyProject.EntityFrameworkCore -c MyProjectDbContext
基本新增資料庫版本 (須從dbContext專案位置執行以下命令)
dotnet ef migrations add newMigrationName當有複數DbContext時需要指定context
dotnet ef migrations add newMigrationName -c mySecondDbContext當DbContext目錄位置與appsetting.json位置不同導致找不到該檔案時(通常為了找連結字串)
dotnet ef migrations add newMigrationName -s ./myStartupProject當出現請安裝 Microsoft.EntityFrameworkCore.Design 請用nuget安裝該套件至dbContext專案
PM> Install Microsoft.EntityFrameworkCore.Design當你需要不同環境變數來讀取對應appsetting..json (dbContext專案必須先實作該功能)
CMD
set ASPNETCORE_ENVIRONMENT=ProductionPowerShell
$env:ASPNETCORE_ENVIRONMENT='Production'
database update
基本更新資料庫版本
dotnet ef database update當有複數DbContext時需要指定context
dotnet ef database update -c myDbContext復原資料庫到特定版本 (複數DbContext時參照第2點)
dotnet ef database update myMigrationName
migrations script
產生SQL語法 (從一開始(0)到myMigrationName之間)
dotnet ef migrations script 0 myMigrationName產生SQL語法 (從myMigrationName到最新)
dotnet ef migrations script myMigrationName當有複數DbContext時需要指定context
dotnet ef migrations script myMigrationName -c myDbContext指定輸出路徑
dotnet ef migrations script myMigrationName -o .\Sql\myMigrationName.sql
migrations remove
移除上一個版本
dotnet ef migrations remove當有複數DbContext時需要指定context
dotnet ef migrations remove -c myDbContext
dotnet tool install --global dotnet-ef
備註
多DB時 所有在 Startup 內有用到的 DBContext ConnectionStrings 都要正確定義在對應環境變數的 appsetting 內 (即使 migrations 只指定某一個 DBContext) 因為 migrations 實際上會執行一次 Startup 導致裡面有用到某連線字串卻又找不到時會報錯
承上 因為 migrations 實際上會執行一次 Startup debug 時可以在 startup 內印出 連接字串、環境變數…等等 執行 migrations 時觀察 log 方便 Debug
執行以上命令時須先把執行中的程式停止
.Net 5 vs .Net Core 3 指令多了一個連字號
Dotnet Core 5
dotnet-ef database updateDotnet Core 3
dotnet ef database update
But, 人生中最重要的就是這個 But!
新版好像兩種都可以用…
參照: Migrations
參照: Running Entity Framework (Core) commands in Rider

PS5
Entity Framework
Migrations
回首頁
本文章從點部落遷移至 Writerside