CLI 工具 dotnet scaffold 為許多 .NET 專案類型建立數據存取 UI,例如 API、Aspire、Blazor、MVC 和 Razor Pages。
dotnet scaffold
可以透過傳遞參數值,以互動方式或以命令行工具的形式執行。
安裝及更新鷹架工具
安裝 .NET SDK。
下列命令會全域安裝 Scaffolder:
dotnet tool install --global Microsoft.dotnet-scaffold
如需 .NET 工具的相關信息,請參閱 如何管理 .NET 工具,以及如何在本機安裝。
若要啟動互動式工具,請執行 dotnet scaffold
。 隨著新增更多功能,UI 會變更。 目前,互動式UI看起來會類似下圖:
若要瀏覽 UI,請使用:
- 使用上下箭頭鍵瀏覽選單項目。
- 按 Enter 鍵以選取已標示的功能表項。
- 選擇並按下 返回 以返回上級選單。
在 Razor Pages 專案中建立和建構數據模型
如果您有下列步驟的任何問題,請參閱 教學課程:使用 ASP.NET Core 建立 Razor Pages Web 應用程式。
- 執行下列命令來建立 Razor Pages 專案,並流覽至 projects 資料夾:
dotnet new webapp -o MyWebApp cd MyWebApp
- 將
Contact
類別新增至MyWebApp
專案:namespace MyWebApp; public class Contact { public int Id { get; set; } public string? Firstname { get; set; } public string? Lastname { get; set; } public string? Email { get; set; } }
- 在 [
dotnet scaffold
] 資料夾中執行MyWebApp
,然後選取 [Razor Pages],然後輸入 return。 - 流覽至 Razor Pages with Entity Framework (CRUD) (dotnet-scaffold-aspnet),然後輸入 return。
- 輸入選取的 MyWebApp (MyWebApp.csproj)回報。
- 在 聯絡人(Contact)中輸入返回。
- 輸入
ContactDbContext
,然後輸入 return。 - 流覽至資料庫提供者,然後輸入 return。
- 選取 CRUD,然後輸入 return。
- 選取發行前版本套件的選項,然後輸入 return。
dotnet scaffold
工具對項目檔進行下列變更:
- 已新增 Entity Framework 的套件參考。
-
Program.cs
已更新以初始化資料庫連接。 -
appsettings.json
已更新連線資訊。 -
ContactDbContext.cs
會建立並新增至專案根目錄。 - Razor CRUD 作業的頁面已新增至 Pages 資料夾。
內容已產生,但資料庫未初始化。 執行下列命令來初始化 DB。
dotnet tool uninstall --global dotnet-ef
dotnet tool install --global dotnet-ef
dotnet ef migrations add initialMigration
dotnet ef database update
在上述命令中:
-
dotnet tool uninstall --global dotnet-ef
卸載dotnet-ef
工具。 卸載可確保已成功安裝最新的工具。 如果未安裝dotnet-ef
,則找不到套件標識碼為 『dotnet-ef』 的工具 錯誤訊息。 您可以忽略此訊息。 -
dotnet tool install --global dotnet-ef
會全域安裝dotnet-ef
工具。 -
dotnet ef migrations add initialMigration
新增初始移轉。 如需詳細資訊,請參閱 第 2 部分,新增模型。 -
dotnet ef database update
會將移轉套用至資料庫。
執行應用程式:
- 在命令行上輸入
dotnet run
,以啟動應用程式。 - 開啟瀏覽器,並瀏覽輸出中指定的 URL 現在正在監聽:http://localhost:wxyz,其中
wxyz
是列出的端口。 - 將
/ContactPages
附加至 URL 的結尾。 - 選取下列項目以測試應用程式:
- 建立新應用程式以創建新的應用程式。
- 嘗試 編輯、詳細數據,以及 刪除 連結。
其他資源
- GitHub 上的 dotnet scaffold 儲存庫
- 如何管理 .NET 工具
-
Microsoft.dotnet-scaffold
NuGet 套件。 - 在 Pages 專案中使用 dotnet scaffold 搭建資料模型Razor