---
name: step-04-backend
description: Generate backend code using MCP scaffold_extension
prev_step: steps/step-03-roles.md
next_step: steps/step-05-frontend.md
---

# Step 4: Backend Generation

## MANDATORY EXECUTION RULES

- ALWAYS use MCP `scaffold_extension` tool - NEVER use templates
- ALWAYS generate Entity + Service + Controller as a unit
- NEVER skip controller generation - API is required
- YOU ARE AN ORCHESTRATOR calling MCP, not a generator
- **NEVER use Write on appsettings*.json** - ALWAYS use Edit (see _resources/config-safety.md)
- **Replace secret VALUES with `<CONFIGURE_HERE>`** - NEVER delete keys or sections

## YOUR TASK

Call the SmartStack MCP `scaffold_extension` tool with type "feature" to generate:
1. Domain Entity with EF Configuration
2. Application Service (Interface + Implementation)
3. API Controller with NavRoute attribute
4. DTOs (Response, Create, Update)

---

## AVAILABLE STATE

From previous steps:

| Variable | Description |
|----------|-------------|
| `{level}` | application, module, section, or resource |
| `{code}` | kebab-case identifier |
| `{full_path}` | Complete navigation path (navRoute) |
| `{labels}` | Object with fr, en, it, de |

---

## EXECUTION SEQUENCE

### 1. Derive Entity Name

Convert `{code}` to PascalCase for entity name:

```
code: "products"        → entityName: "Product"
code: "order-items"     → entityName: "OrderItem"
code: "user-profiles"   → entityName: "UserProfile"
```

### 2. Determine Table Prefix and Controller Folder

See [references/backend-table-prefix-mapping.md](../references/backend-table-prefix-mapping.md) for:
- Table prefix priority (feature.json vs. fallback)
- Application-to-prefix mapping table
- Feature.json detection and extraction
- Controller folder organization
- Store `{controller_folder}` from the mapping

### 3. Call MCP scaffold_extension

```
Tool: mcp__smartstack__scaffold_extension
Args:
  type: "feature"
  name: "{entityName}"  # PascalCase
  options:
    navRoute: "{full_path}"
    tablePrefix: "{prefix}"
    schema: "core"
    withDtos: true
    withValidation: true
    withRepository: false  # Use service pattern
    skipComponent: true    # Frontend in next step
    dryRun: false
```

### 4. Parse MCP Response

The tool generates (paths organized by navRoute hierarchy `{application}.{module}`):
- `Domain/{Application}/{Module}/{EntityName}.cs` - Entity with BaseEntity
- `Infrastructure/Persistence/Configurations/{Application}/{Module}/{EntityName}Configuration.cs` - EF Config
- `Application/Common/Interfaces/I{EntityName}Service.cs` - Service Interface
- `Infrastructure/Services/{Application}/{Module}/{EntityName}Service.cs` - Service Implementation
- `Api/Controllers/{controller_folder}/{Application}/{EntityName}Controller.cs` - REST Controller
- `Application/{Application}/{Module}/DTOs/{EntityName}ResponseDto.cs` - Response DTO
- `Application/{Application}/{Module}/DTOs/Create{EntityName}Dto.cs` - Create request
- `Application/{Application}/{Module}/DTOs/Update{EntityName}Dto.cs` - Update request

### 5-7. Present Output, Entity Seeding & Store Info

See [references/backend-seeding-and-dto-output.md](../references/backend-seeding-and-dto-output.md) for:
- Output formatting by layer (Domain, Infrastructure, Application, API)
- Entity seeding questions and responses
- Entity info storage for frontend generation

---

## CONTROLLER NAVROUTE AND FOLDER HIERARCHY

See [references/backend-controller-hierarchy.md](../references/backend-controller-hierarchy.md) for the complete reference:
- Controller file organization (Admin/Business/Support/User folders)
- Context-to-folder mapping table
- NavRoute attribute C# template with RequirePermission

---

## MCP RESPONSE HANDLING

### Success Case

If MCP returns successfully:
- Display all generated files
- Show DbSet and DI registration instructions
- Ask about entity seeding (section 6)
- Store entity info for frontend
- Proceed to step-05-frontend.md

### Error Case

If MCP call fails:
- Display error message
- Suggest checking entity name format
- Do NOT proceed automatically

---

## POST-GENERATION VERIFICATION (MANDATORY)

**Before proceeding to step-05, run ALL checks.**

See [references/backend-verification.md](../references/backend-verification.md) for the complete verification checklist:

| Check | Type | What |
|-------|------|------|
| 1. Backend Build | BLOCKING | `dotnet build --no-restore` must succeed |
| 2. DbSet Registration | BLOCKING | `DbSet<{EntityName}>` in DbContext |
| 3. DI Registration | BLOCKING | `I{EntityName}Service` in DependencyInjection.cs |
| 4. RequirePermission | BLOCKING | All HTTP actions have `[RequirePermission]` |
| 5. Entity Configuration | BLOCKING | Table prefix, HasKey, HasIndex |
| 5b. Seeding Infrastructure | BLOCKING (first entity) | SeedConstants + DevDataSeeder + DI |
| 5c. SqlObjects Directory | BLOCKING (first entity) | SqlObjectHelper + Functions/ + .csproj EmbeddedResource |
| 6. Convention Validation | RECOMMENDED | `mcp__smartstack__validate_conventions` |

IF any BLOCKING check fails: Fix before proceeding to step-05.

---

## SUCCESS METRICS

- MCP scaffold_extension called successfully
- Entity, Service, Controller generated
- DTOs generated
- NavRoute attribute included
- Entity seeding offered to user (SeedData.cs + DevDataSeeder if accepted)
- Entity info stored for frontend
- Post-generation verification passed (all 7 checks: 5 original + 5b Seeding + 5c SqlObjects)
- Proceeded to step-05-frontend.md

## FAILURE MODES

- MCP call failed (display error, stop)
- Invalid entity name (must be PascalCase)
- Invalid navRoute format

---

## NEXT STEP

After backend code is generated and entity seeding is handled,
proceed to `./step-05-frontend.md`
