create-datadriven-aspnetcore

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Generate 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
dotnet
CLI commands for build, restore, and migrations are still expected.
生成ASP.NET Core搭建代码——包括控制器、视图、Razor Pages、Blazor组件、Minimal API端点。生成的代码会匹配项目现有CSS框架、布局规范和编码模式。无需使用基于CLI的搭建/代码生成工具;但仍需使用标准
dotnet
CLI命令进行构建、还原和迁移操作。

When 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

输入项

InputRequiredDescription
Scaffolding requestYesNatural-language description of what to scaffold (see format below)
Project file pathYesFull path to the target
.csproj
file
Solution root pathRecommendedPath to the solution root for multi-project solutions
输入项是否必填描述
搭建请求对搭建内容的自然语言描述(格式见下文)
项目文件路径目标
.csproj
文件的完整路径
解决方案根路径推荐多项目解决方案的根路径

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
  1. Inspect the project file,
    Program.cs
    , target model, validation attributes, navigation properties, and foreign keys before editing.
  2. Reuse the requested existing
    DbContext
    ; otherwise create the requested context. Add only the required provider package and register it with
    AddDbContext
    using the requested provider and connection string. You will need to add Microsoft.EntityFrameworkCore.Design (PrivateAssets="all") when migrations are needed and it's missing.
  3. Generate complete CRUD for the requested entity and every required parent entity: list, details, create, edit, and delete.
  4. Use the EF migration lifecycle: create a migration and apply it. Never call
    EnsureCreated
    or seed the database in
    Program.cs
    .
  5. Restore, build, and test the generated project. Fix errors before reporting completion.
MVC, Razor Pages, and Blazor
  1. Inspect the existing layout, CSS, and representative UI before generating markup.
  2. 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.
  3. Match the existing UI framework and conventions; preserve existing render-mode configuration for Blazor.
Minimal APIs
  1. Use a route group for each resource and map
    GET
    (list and by ID),
    POST
    ,
    PUT
    , and
    DELETE
    endpoints for both child and required-parent resources.
  2. Add OpenAPI metadata to every endpoint: unique name, tags, description, success/error response metadata, and
    WithOpenApi
    when OpenAPI is enabled.
  3. Create an executable
    .http
    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.
按顺序完成适用的检查清单。当必填外键需要父资源时,不能仅创建请求的子资源就停止。
所有EF搭建工具
  1. 在编辑前检查项目文件、
    Program.cs
    、目标模型、验证属性、导航属性和外键。
  2. 复用请求的现有
    DbContext
    ;否则创建请求的上下文。仅添加所需的提供程序包,并使用请求的提供程序和连接字符串通过
    AddDbContext
    注册。当需要迁移且缺少Microsoft.EntityFrameworkCore.Design时,添加该包(PrivateAssets="all")。
  3. 为请求的实体和每个必填父实体生成完整的CRUD功能:列表、详情、创建、编辑和删除。
  4. 使用EF迁移生命周期:创建迁移并应用。切勿在
    Program.cs
    中调用
    EnsureCreated
    或初始化数据库数据。
  5. 还原、构建并测试生成的项目。在报告完成前修复所有错误。
MVC、Razor Pages和Blazor
  1. 在生成标记前检查现有布局、CSS和代表性UI。
  2. 生成完整的子资源和必填父资源UI流程,包括每个资源的导航路径,以便用户在创建子资源前先创建父资源。
  3. 匹配现有UI框架和规范;保留Blazor的现有渲染模式配置。
Minimal API
  1. 为每个资源使用路由组,并为子资源和必填父资源映射
    GET
    (列表和按ID查询)、
    POST
    PUT
    DELETE
    端点。
  2. 为每个端点添加OpenAPI元数据:唯一名称、标签、描述、成功/错误响应元数据,以及启用OpenAPI时的
    WithOpenApi
  3. 创建包含所有CRUD请求的可执行
    .http
    文件。先创建父记录,在子请求中捕获或明确复用返回的ID,并按依赖顺序执行请求。

Step 2: Discover UI Style (non-API scaffolders only)

步骤2:识别UI样式(仅非API搭建工具)

Skip this step for API controllers and Minimal API endpoints.
  1. Inspect the project's layout file (
    _Layout.cshtml
    ,
    MainLayout.razor
    , or equivalent)
  2. Inspect the main CSS file (
    site.css
    ,
    app.css
    , Tailwind config, etc.)
  3. 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端点跳过此步骤。
  1. 检查项目的布局文件(
    _Layout.cshtml
    MainLayout.razor
    或等效文件)
  2. 检查主CSS文件(
    site.css
    app.css
    、Tailwind配置等)
  3. 检查项目中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.
  • [SupplyParameterFromForm]
    properties MUST use
    = new()
    (not
    null!
    ) — prevents
    EditForm
    crash on initial GET
  • Program.cs
    must chain
    .AddInteractiveServerComponents()
    on
    AddRazorComponents()
    and
    .AddInteractiveServerRenderMode()
    on
    MapRazorComponents<App>()
    . only add interactive server services/render mode when the generated components actually use @rendermode InteractiveServer (or the project already does).
  • Do not replace existing chained render mode calls (e.g.,
    .AddInteractiveWebAssemblyRenderMode()
    )
非Blazor搭建工具跳过此步骤。
  • [SupplyParameterFromForm]
    属性必须使用
    = new()
    (而非
    null!
    )——避免初始GET请求时
    EditForm
    崩溃
  • Program.cs
    必须在
    AddRazorComponents()
    后链式调用
    .AddInteractiveServerComponents()
    ,并在
    MapRazorComponents<App>()
    后链式调用
    .AddInteractiveServerRenderMode()
    。仅当生成的组件实际使用@rendermode InteractiveServer(或项目已使用)时,才添加交互式服务器服务/渲染模式。
  • 不要替换现有的链式渲染模式调用(例如
    .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
    RuntimeCompilation
    , or other convenience packages)
  • 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:
  • .WithName("GetTodoItems")
    — unique operation ID for each endpoint
  • .WithTags("TodoItems")
    — group endpoints by resource
  • .WithDescription("Returns all todo items")
    — human-readable summary
  • .Produces<List<TodoItem>>(StatusCodes.Status200OK)
    — document success response type
  • .Produces(StatusCodes.Status404NotFound)
    — document error responses
  • .ProducesValidationProblem()
    — for endpoints that validate input
  • .WithOpenApi()
    — opt the endpoint into OpenAPI generation (if not already globally enabled)
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文档具有描述性和实用性:
  • .WithName("GetTodoItems")
    ——每个端点的唯一操作ID
  • .WithTags("TodoItems")
    ——按资源分组端点
  • .WithDescription("Returns all todo items")
    ——人类可读的摘要
  • .Produces<List<TodoItem>>(StatusCodes.Status200OK)
    ——记录成功响应类型
  • .Produces(StatusCodes.Status404NotFound)
    ——记录错误响应
  • .ProducesValidationProblem()
    ——用于验证输入的端点
  • .WithOpenApi()
    ——将端点纳入OpenAPI生成(如果未全局启用)
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
    Program.cs
    — always use migrations
  • For
    dotnet ef
    : prefer
    dotnet tool restore
    from a local tool manifest. Only install globally if no manifest exists
  • Inspect the model for navigation properties and foreign keys. Ensure CRUD endpoints/pages exist for referenced entities
  • For API scaffolders: the
    .http
    file MUST create parent entities before child entities. Use FK values consistent with creation order
如果搭建请求不涉及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.
  1. Create a
    .http
    file named
    {ModelName}.http
    in the project directory. If a file with that name exists, append a numeric suffix (
    Product2.http
    ,
    Product3.http
    ) until unique
  2. Include sample requests for every CRUD endpoint scaffolded, including endpoints for parent/dependent entities
  3. Every request must target the correct URL path matching an actual mapped endpoint
  4. Request labels must accurately describe the action (e.g., "Create a category" must POST to the categories endpoint)
  5. Order requests by dependency: create parent entities before child entities
  6. 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
  7. 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搭建工具跳过此步骤。
  1. 在项目目录中创建名为
    {ModelName}.http
    的文件。如果该名称的文件已存在,添加数字后缀(
    Product2.http
    Product3.http
    )直至唯一
  2. 包含所有搭建的CRUD端点的示例请求,包括父/依赖实体的端点
  3. 每个请求必须指向与实际映射端点匹配的正确URL路径
  4. 请求标签必须准确描述操作(例如“Create a category”必须POST到分类端点)
  5. 按依赖顺序排列请求:先创建父实体,再创建子实体
  6. 尽可能使用HTTP客户端的变量/模板功能捕获父创建响应中的ID,并在子实体POST负载中复用作为外键值
  7. 如果客户端无法捕获响应值,添加注释说明运行父创建请求后必须更新哪些外键ID;不要留下不切实际的占位符或假设的外键值,这些值在执行请求时与实际父记录不对应

Step 7: Verify

步骤7:验证

  1. Run
    dotnet restore && dotnet build
    from the project directory
  2. 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.
  3. If API scaffolder:
    • Inspect
      Properties/launchSettings.json
      — if a profile named
      https
      exists, use
      dotnet run --launch-profile https
    • Execute EVERY
      .http
      request one at a time in dependency order
    • Report method, URL, and status code for each request
    • Stop and fix if any request returns non-2xx
  4. Fix all errors until a clean build succeeds
  1. 从项目目录运行
    dotnet restore && dotnet build
  2. 如果使用Entity Framework且是首次验证:
    • 运行
      dotnet ef migrations add InitialCreate
    • 运行
      dotnet ef database update
    • 如果多次运行此操作,需要将“InitialCreate”改为其他名称,因为EF Core要求迁移名称唯一。
  3. 如果是API搭建工具:
    • 检查
      Properties/launchSettings.json
      ——如果存在名为
      https
      的配置文件,使用
      dotnet run --launch-profile https
    • 按依赖顺序逐个执行所有
      .http
      请求
    • 报告每个请求的方法、URL和状态码
    • 如果任何请求返回非2xx状态码,停止并修复
  4. 修复所有错误,直至构建成功且无错误

Validation

验证清单

  • All generated files match the project's existing CSS framework and conventions
  • dotnet build
    succeeds with zero errors
  • EF migrations apply cleanly (if applicable)
  • All
    .http
    requests return 2xx status codes (if API scaffolder)
  • No forbidden packages were added (
    RuntimeCompilation
    , etc.)
  • No CLI scaffolding tools were invoked
  • Blazor
    [SupplyParameterFromForm]
    properties use
    = new()
    (if Blazor scaffolder)
  • 所有生成文件匹配项目现有CSS框架和规范
  • dotnet build
    执行成功,无错误
  • EF迁移应用成功(如适用)
  • 所有
    .http
    请求返回2xx状态码(如为API搭建工具)
  • 未添加禁用的包(
    RuntimeCompilation
    等)
  • 未调用CLI搭建工具
  • Blazor的
    [SupplyParameterFromForm]
    属性使用
    = new()
    (如为Blazor搭建工具)

Common Pitfalls

常见陷阱

PitfallSolution
Generated UI doesn't match project's CSS frameworkAlways inspect layout and CSS files before generating code (Step 2)
Blazor
EditForm
crashes on initial GET
Use
= new()
not
null!
for
[SupplyParameterFromForm]
properties
EF migration fails due to missing parent entity CRUDScaffold CRUD for FK-dependent entities when request mentions foreign keys
.http
file has wrong FK values
Order requests by dependency; use values consistent with creation order
dotnet ef
not found
Try
dotnet tool restore
first; only install globally as fallback
Added unnecessary packagesOnly add packages explicitly required for the scaffolded functionality
Generated code uses different naming conventionsInspect existing project files to match naming patterns before generating
陷阱解决方案
生成的UI与项目CSS框架不匹配生成代码前始终检查布局和CSS文件(步骤2)
Blazor
EditForm
在初始GET请求时崩溃
[SupplyParameterFromForm]
属性使用
= new()
而非
null!
EF迁移因缺少父实体CRUD而失败当请求提及外键时,为依赖外键的实体搭建CRUD功能
.http
文件外键值错误
按依赖顺序排列请求;使用与创建顺序一致的值
找不到
dotnet ef
先尝试
dotnet tool restore
;仅作为回退方案全局安装
添加了不必要的包仅添加搭建功能明确需要的包
生成代码使用不同的命名规范生成代码前检查现有项目文件以匹配命名模式

References

参考资料