https://learn.microsoft.com/zh-tw/ef/core/what-is-new/ef-core-8.0/whatsnew
安裝 dotnet-ef 工具,使用 Migrations 來追蹤 Model 的變化,並且更新 DB Schema。
dotnet tool install --global dotnet-ef
dotnet ef migrations add InitialCreate
dotnet ef database update
- Scaffolding (Reverse Engineering)
dotnet ef dbcontext scaffold "Server=DB_addr;Database=DB_name;User ID=username;
password=; Trusted_Connection=True;Integrated Security=False;TrustServerCertificate=True;" Microsoft.EntityFrameworkCore.SqlServer -d -o Model/Entities
- 在本機開發環境使用 User Secrets
dotnet user-secrets init
dotnet user-secrets set "DbPassword" "pass123"
參考 https://learn.microsoft.com/zh-tw/aspnet/core/security/app-secrets?view=aspnetcore-8.0&tabs=windows
- 在生產環境要從 appsettings.json 讀取
{
"DbPassword": "pass123"
}
- MyContext.cs
override void OnConfiguring 方法,從 Configuration 取得 ConnectionStrings 和 DbPassword 並使用 SqlConnectionStringBuilder