create-datadriven-aspnetcore
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGenerate or Scaffold ASP.NET Core Code
生成或搭建ASP.NET Core代码
Generate ASP.NET Core scaffolded code — controllers, views, Razor Pages, Blazor components, Minimal API endpoints. The generated code matches the project's existing CSS framework, layout conventions, and coding patterns. No CLI-based scaffolding/code-generation tools are used; standard CLI commands for build, restore, and migrations are still expected.
dotnet生成ASP.NET Core搭建代码——包括控制器、视图、Razor Pages、Blazor组件、Minimal API端点。生成的代码会匹配项目现有CSS框架、布局规范和编码模式。无需使用基于CLI的搭建/代码生成工具;但仍需使用标准 CLI命令进行构建、还原和迁移操作。
dotnetWhen to Use
适用场景
- Adding CRUD pages, views, or components for a model in an ASP.NET Core project
- Scaffolding API controllers or Minimal API endpoints with Entity Framework Core
- Generating Razor Pages, MVC views, or Blazor components backed by a DbContext
- 在ASP.NET Core项目中为模型添加CRUD页面、视图或组件
- 搭建基于Entity Framework Core的API控制器或Minimal API端点
- 生成基于DbContext的Razor Pages、MVC视图或Blazor组件
When Not to Use
不适用场景
- The project is not an ASP.NET Core project
- You need to scaffold non-web artifacts (class libraries, console apps, etc.)
- 项目并非ASP.NET Core项目
- 需要搭建非Web工件(类库、控制台应用等)
Inputs
输入项
| Input | Required | Description |
|---|---|---|
| Scaffolding request | Yes | Natural-language description of what to scaffold (see format below) |
| Project file path | Yes | Full path to the target |
| Solution root path | Recommended | Path to the solution root for multi-project solutions |
| 输入项 | 是否必填 | 描述 |
|---|---|---|
| 搭建请求 | 是 | 对搭建内容的自然语言描述(格式见下文) |
| 项目文件路径 | 是 | 目标 |
| 解决方案根路径 | 推荐 | 多项目解决方案的根路径 |
Scaffolding Request Format
搭建请求格式
The scaffolding request should be a natural-language description of what to scaffold. The request must include the target project path and enough detail for the agent to generate the correct code. Examples:
Razor Pages with EF:
Scaffold Razor Pages with CRUD for the `<ModelName>` model (from `<Namespace>`) in project `<path-to-csproj>`.
Create a new DbContext `<DbContextName>` using <database-provider>.
Also scaffold CRUD for any entity that `<ModelName>` depends on via required foreign keys, so parent entities can be created first.Blazor CRUD components:
Scaffold Blazor CRUD components for the `<ModelName>` model (from `<Namespace>`) in project `<path-to-csproj>`.
Create a new DbContext `<DbContextName>` using <database-provider>.Minimal API endpoints:
Scaffold Minimal API endpoints for the `<ModelName>` model (from `<Namespace>`) in project `<path-to-csproj>`.
Name the endpoints class `<EndpointsClassName>`.
Create a new DbContext `<DbContextName>` using <database-provider>.
Enable OpenAPI support.MVC Controller with views:
Scaffold an MVC controller with views and Entity Framework for the `<ModelName>` model (from `<Namespace>`) in project `<path-to-csproj>`.
Name the controller `<ControllerName>`.
Use existing DbContext `<DbContextName>`.
Generate views.Empty items (no EF):
Scaffold an empty Razor Page named `<PageName>` in project `<path-to-csproj>`.搭建请求应为对搭建内容的自然语言描述,必须包含目标项目路径和足够细节,以便生成正确代码。示例:
基于EF的Razor Pages:
为项目`<path-to-csproj>`中的`<Namespace>`命名空间下的`<ModelName>`模型搭建带CRUD功能的Razor Pages。
使用<database-provider>创建新的DbContext `<DbContextName>`。
同时为`<ModelName>`通过必填外键依赖的所有实体搭建CRUD功能,以便先创建父实体。Blazor CRUD组件:
为项目`<path-to-csproj>`中的`<Namespace>`命名空间下的`<ModelName>`模型搭建Blazor CRUD组件。
使用<database-provider>创建新的DbContext `<DbContextName>`。Minimal API端点:
为项目`<path-to-csproj>`中的`<Namespace>`命名空间下的`<ModelName>`模型搭建Minimal API端点。
将端点类命名为`<EndpointsClassName>`。
使用<database-provider>创建新的DbContext `<DbContextName>`。
启用OpenAPI支持。带视图的MVC控制器:
为项目`<path-to-csproj>`中的`<Namespace>`命名空间下的`<ModelName>`模型搭建带视图和Entity Framework的MVC控制器。
将控制器命名为`<ControllerName>`。
使用现有DbContext `<DbContextName>`。
生成视图。空项(无EF):
在项目`<path-to-csproj>`中搭建名为`<PageName>`的空Razor Page。Workflow
工作流程
Step 1: Understand the Scaffolding Request
步骤1:理解搭建请求
Parse the scaffolding request to identify:
- Scaffolder type: Razor Pages, Blazor components, MVC controller, Minimal API, empty page/view/component
- Model class and its namespace
- DbContext: new or existing, database provider (SQLite, SQL Server, etc.)
- Named items: controller name, endpoints class name, page name, view name, area name
- Options: OpenAPI, async actions, partial view, custom layout
- FK scope: whether to also scaffold CRUD for parent entities referenced by required foreign keys
解析搭建请求,确定:
- 搭建类型:Razor Pages、Blazor组件、MVC控制器、Minimal API、空页面/视图/组件
- 模型类及其命名空间
- DbContext:新建或现有,数据库提供程序(SQLite、SQL Server等)
- 命名项:控制器名称、端点类名称、页面名称、视图名称、区域名称
- 选项:OpenAPI、异步操作、局部视图、自定义布局
- 外键范围:是否同时为必填外键引用的父实体搭建CRUD功能
Execution Checklists
执行检查清单
Complete the applicable checklist in order. Do not stop after creating only the requested child resource when a required foreign key makes a parent resource necessary.
All EF scaffolders
- Inspect the project file, , target model, validation attributes, navigation properties, and foreign keys before editing.
Program.cs - Reuse the requested existing ; otherwise create the requested context. Add only the required provider package and register it with
DbContextusing the requested provider and connection string. You will need to add Microsoft.EntityFrameworkCore.Design (PrivateAssets="all") when migrations are needed and it's missing.AddDbContext - Generate complete CRUD for the requested entity and every required parent entity: list, details, create, edit, and delete.
- Use the EF migration lifecycle: create a migration and apply it. Never call or seed the database in
EnsureCreated.Program.cs - Restore, build, and test the generated project. Fix errors before reporting completion.
MVC, Razor Pages, and Blazor
- Inspect the existing layout, CSS, and representative UI before generating markup.
- Generate the complete child and required-parent UI flows, including a navigation path to each resource so users can create a parent before creating a child.
- Match the existing UI framework and conventions; preserve existing render-mode configuration for Blazor.
Minimal APIs
- Use a route group for each resource and map (list and by ID),
GET,POST, andPUTendpoints for both child and required-parent resources.DELETE - Add OpenAPI metadata to every endpoint: unique name, tags, description, success/error response metadata, and when OpenAPI is enabled.
WithOpenApi - Create an executable file with every CRUD request. Create parent records first, capture or clearly reuse their returned IDs in child requests, and run the requests in dependency order.
.http
按顺序完成适用的检查清单。当必填外键需要父资源时,不能仅创建请求的子资源就停止。
所有EF搭建工具
- 在编辑前检查项目文件、、目标模型、验证属性、导航属性和外键。
Program.cs - 复用请求的现有;否则创建请求的上下文。仅添加所需的提供程序包,并使用请求的提供程序和连接字符串通过
DbContext注册。当需要迁移且缺少Microsoft.EntityFrameworkCore.Design时,添加该包(PrivateAssets="all")。AddDbContext - 为请求的实体和每个必填父实体生成完整的CRUD功能:列表、详情、创建、编辑和删除。
- 使用EF迁移生命周期:创建迁移并应用。切勿在中调用
Program.cs或初始化数据库数据。EnsureCreated - 还原、构建并测试生成的项目。在报告完成前修复所有错误。
MVC、Razor Pages和Blazor
- 在生成标记前检查现有布局、CSS和代表性UI。
- 生成完整的子资源和必填父资源UI流程,包括每个资源的导航路径,以便用户在创建子资源前先创建父资源。
- 匹配现有UI框架和规范;保留Blazor的现有渲染模式配置。
Minimal API
- 为每个资源使用路由组,并为子资源和必填父资源映射(列表和按ID查询)、
GET、POST和PUT端点。DELETE - 为每个端点添加OpenAPI元数据:唯一名称、标签、描述、成功/错误响应元数据,以及启用OpenAPI时的。
WithOpenApi - 创建包含所有CRUD请求的可执行文件。先创建父记录,在子请求中捕获或明确复用返回的ID,并按依赖顺序执行请求。
.http
Step 2: Discover UI Style (non-API scaffolders only)
步骤2:识别UI样式(仅非API搭建工具)
Skip this step for API controllers and Minimal API endpoints.
- Inspect the project's layout file (,
_Layout.cshtml, or equivalent)MainLayout.razor - Inspect the main CSS file (,
site.css, Tailwind config, etc.)app.css - Inspect 1–2 existing pages, views, or components in the project
All generated files MUST match the existing UI framework, CSS classes, and conventions. If Bootstrap is used, generate Bootstrap markup. If Tailwind is used, generate Tailwind markup.
API控制器和Minimal API端点跳过此步骤。
- 检查项目的布局文件(、
_Layout.cshtml或等效文件)MainLayout.razor - 检查主CSS文件(、
site.css、Tailwind配置等)app.css - 检查项目中1-2个现有页面、视图或组件
所有生成的文件必须匹配现有UI框架、CSS类和规范。如果使用Bootstrap,生成Bootstrap标记;如果使用Tailwind,生成Tailwind标记。
Step 3: Apply Blazor-Specific Rules (Blazor scaffolders only)
步骤3:应用Blazor特定规则(仅Blazor搭建工具)
Skip this step for non-Blazor scaffolders.
- properties MUST use
[SupplyParameterFromForm](not= new()) — preventsnull!crash on initial GETEditForm - must chain
Program.cson.AddInteractiveServerComponents()andAddRazorComponents()on.AddInteractiveServerRenderMode(). only add interactive server services/render mode when the generated components actually use @rendermode InteractiveServer (or the project already does).MapRazorComponents<App>() - Do not replace existing chained render mode calls (e.g., )
.AddInteractiveWebAssemblyRenderMode()
非Blazor搭建工具跳过此步骤。
- 属性必须使用
[SupplyParameterFromForm](而非= new())——避免初始GET请求时null!崩溃EditForm - 必须在
Program.cs后链式调用AddRazorComponents(),并在.AddInteractiveServerComponents()后链式调用MapRazorComponents<App>()。仅当生成的组件实际使用@rendermode InteractiveServer(或项目已使用)时,才添加交互式服务器服务/渲染模式。.AddInteractiveServerRenderMode() - 不要替换现有的链式渲染模式调用(例如)
.AddInteractiveWebAssemblyRenderMode()
Step 4: Generate Code
步骤4:生成代码
Generate all code files manually. Follow these constraints:
- DO NOT use any scaffolding CLI tools
- DO NOT add packages beyond those required for the scaffolded functionality (e.g., do not add , or other convenience packages)
RuntimeCompilation - Match the coding style of existing files in the project (naming conventions, indentation, namespace patterns)
手动生成所有代码文件。遵循以下约束:
- 禁止使用任何搭建CLI工具
- 禁止添加超出搭建功能所需的包(例如不要添加或其他便利包)
RuntimeCompilation - 匹配项目中现有文件的编码风格(命名规范、缩进、命名空间模式)
Enrich API Endpoints with OpenAPI Metadata (API scaffolders only)
为API端点添加OpenAPI元数据(仅API搭建工具)
When generating Minimal API or MVC API endpoints with OpenAPI support enabled, add rich metadata to every endpoint so the OpenAPI document is descriptive and useful:
- — unique operation ID for each endpoint
.WithName("GetTodoItems") - — group endpoints by resource
.WithTags("TodoItems") - — human-readable summary
.WithDescription("Returns all todo items") - — document success response type
.Produces<List<TodoItem>>(StatusCodes.Status200OK) - — document error responses
.Produces(StatusCodes.Status404NotFound) - — for endpoints that validate input
.ProducesValidationProblem() - — opt the endpoint into OpenAPI generation (if not already globally enabled)
.WithOpenApi()
Example for a Minimal API GET endpoint:
csharp
group.MapGet("/", async (TodoDbContext db) =>
await db.TodoItems.ToListAsync())
.WithName("GetAllTodoItems")
.WithTags("TodoItems")
.WithDescription("Returns all todo items")
.Produces<List<TodoItem>>(StatusCodes.Status200OK);当生成启用OpenAPI支持的Minimal API或MVC API端点时,为每个端点添加丰富的元数据,使OpenAPI文档具有描述性和实用性:
- ——每个端点的唯一操作ID
.WithName("GetTodoItems") - ——按资源分组端点
.WithTags("TodoItems") - ——人类可读的摘要
.WithDescription("Returns all todo items") - ——记录成功响应类型
.Produces<List<TodoItem>>(StatusCodes.Status200OK) - ——记录错误响应
.Produces(StatusCodes.Status404NotFound) - ——用于验证输入的端点
.ProducesValidationProblem() - ——将端点纳入OpenAPI生成(如果未全局启用)
.WithOpenApi()
Minimal API GET端点示例:
csharp
group.MapGet("/", async (TodoDbContext db) =>
await db.TodoItems.ToListAsync())
.WithName("GetAllTodoItems")
.WithTags("TodoItems")
.WithDescription("Returns all todo items")
.Produces<List<TodoItem>>(StatusCodes.Status200OK);Step 5: Set Up Entity Framework (if applicable)
步骤5:设置Entity Framework(如适用)
Skip this step if the scaffolding request does not involve Entity Framework.
- DO NOT seed the database in — always use migrations
Program.cs - For : prefer
dotnet effrom a local tool manifest. Only install globally if no manifest existsdotnet tool restore - Inspect the model for navigation properties and foreign keys. Ensure CRUD endpoints/pages exist for referenced entities
- For API scaffolders: the file MUST create parent entities before child entities. Use FK values consistent with creation order
.http
如果搭建请求不涉及Entity Framework,跳过此步骤。
- 禁止在中初始化数据库数据——始终使用迁移
Program.cs - 对于:优先从本地工具清单执行
dotnet ef。仅当没有清单时才全局安装dotnet tool restore - 检查模型的导航属性和外键。确保引用的实体存在CRUD端点/页面
- 对于API搭建工具:文件必须先创建父实体,再创建子实体。使用与创建顺序一致的外键值
.http
Step 6: Generate .http File (API scaffolders only)
步骤6:生成.http文件(仅API搭建工具)
Skip this step for non-API scaffolders.
- Create a file named
.httpin the project directory. If a file with that name exists, append a numeric suffix ({ModelName}.http,Product2.http) until uniqueProduct3.http - Include sample requests for every CRUD endpoint scaffolded, including endpoints for parent/dependent entities
- Every request must target the correct URL path matching an actual mapped endpoint
- Request labels must accurately describe the action (e.g., "Create a category" must POST to the categories endpoint)
- Order requests by dependency: create parent entities before child entities
- When possible, capture IDs from parent creation responses using your HTTP client's variable/templating features and reuse them as foreign key values in child-entity POST payloads
- If your client cannot capture response values, add comments indicating which FK IDs must be updated after running the parent creation requests; do not leave unrealistic placeholder or assumed FK values that do not correspond to actual parent records when executing the requests
非API搭建工具跳过此步骤。
- 在项目目录中创建名为的文件。如果该名称的文件已存在,添加数字后缀(
{ModelName}.http、Product2.http)直至唯一Product3.http - 包含所有搭建的CRUD端点的示例请求,包括父/依赖实体的端点
- 每个请求必须指向与实际映射端点匹配的正确URL路径
- 请求标签必须准确描述操作(例如“Create a category”必须POST到分类端点)
- 按依赖顺序排列请求:先创建父实体,再创建子实体
- 尽可能使用HTTP客户端的变量/模板功能捕获父创建响应中的ID,并在子实体POST负载中复用作为外键值
- 如果客户端无法捕获响应值,添加注释说明运行父创建请求后必须更新哪些外键ID;不要留下不切实际的占位符或假设的外键值,这些值在执行请求时与实际父记录不对应
Step 7: Verify
步骤7:验证
- Run from the project directory
dotnet restore && dotnet build - If Entity Framework is used and this is the first verification:
- Run
dotnet ef migrations add InitialCreate - Run
dotnet ef database update - You will need to change "InitialCreate" to something else if you run this more than once, as EF Core requires unique migration names.
- Run
- If API scaffolder:
- Inspect — if a profile named
Properties/launchSettings.jsonexists, usehttpsdotnet run --launch-profile https - Execute EVERY request one at a time in dependency order
.http - Report method, URL, and status code for each request
- Stop and fix if any request returns non-2xx
- Inspect
- Fix all errors until a clean build succeeds
- 从项目目录运行
dotnet restore && dotnet build - 如果使用Entity Framework且是首次验证:
- 运行
dotnet ef migrations add InitialCreate - 运行
dotnet ef database update - 如果多次运行此操作,需要将“InitialCreate”改为其他名称,因为EF Core要求迁移名称唯一。
- 运行
- 如果是API搭建工具:
- 检查——如果存在名为
Properties/launchSettings.json的配置文件,使用httpsdotnet run --launch-profile https - 按依赖顺序逐个执行所有请求
.http - 报告每个请求的方法、URL和状态码
- 如果任何请求返回非2xx状态码,停止并修复
- 检查
- 修复所有错误,直至构建成功且无错误
Validation
验证清单
- All generated files match the project's existing CSS framework and conventions
- succeeds with zero errors
dotnet build - EF migrations apply cleanly (if applicable)
- All requests return 2xx status codes (if API scaffolder)
.http - No forbidden packages were added (, etc.)
RuntimeCompilation - No CLI scaffolding tools were invoked
- Blazor properties use
[SupplyParameterFromForm](if Blazor scaffolder)= new()
- 所有生成文件匹配项目现有CSS框架和规范
- 执行成功,无错误
dotnet build - EF迁移应用成功(如适用)
- 所有请求返回2xx状态码(如为API搭建工具)
.http - 未添加禁用的包(等)
RuntimeCompilation - 未调用CLI搭建工具
- Blazor的属性使用
[SupplyParameterFromForm](如为Blazor搭建工具)= new()
Common Pitfalls
常见陷阱
| Pitfall | Solution |
|---|---|
| Generated UI doesn't match project's CSS framework | Always inspect layout and CSS files before generating code (Step 2) |
Blazor | Use |
| EF migration fails due to missing parent entity CRUD | Scaffold CRUD for FK-dependent entities when request mentions foreign keys |
| Order requests by dependency; use values consistent with creation order |
| Try |
| Added unnecessary packages | Only add packages explicitly required for the scaffolded functionality |
| Generated code uses different naming conventions | Inspect existing project files to match naming patterns before generating |
| 陷阱 | 解决方案 |
|---|---|
| 生成的UI与项目CSS框架不匹配 | 生成代码前始终检查布局和CSS文件(步骤2) |
Blazor | 对 |
| EF迁移因缺少父实体CRUD而失败 | 当请求提及外键时,为依赖外键的实体搭建CRUD功能 |
| 按依赖顺序排列请求;使用与创建顺序一致的值 |
找不到 | 先尝试 |
| 添加了不必要的包 | 仅添加搭建功能明确需要的包 |
| 生成代码使用不同的命名规范 | 生成代码前检查现有项目文件以匹配命名模式 |
References
参考资料
- Entity Framework Core DbContext Lifetime, Configuration, and Initialization
- OpenAPI overview in ASP.NET Core — .NET 10 specific; similar pages exist for other versions
- Entity Framework Core DbContext 生命周期、配置和初始化
- ASP.NET Core中的OpenAPI概述 —— .NET 10特定;其他版本有类似页面