---
name: step-06-migration
description: Create EF Core migration and finalize application setup
prev_step: steps/step-05-frontend.md
next_step: steps/step-07-tests.md
---

# Step 6: Migration & Finalization

## MANDATORY EXECUTION RULES

- ALWAYS use MCP `suggest_migration` to get proper migration name
- ALWAYS use `/efcore:migration` skill for migration creation
- NEVER use raw SQL in migrations
- YOU ARE AN ORCHESTRATOR, finalizing the application setup

## YOUR TASK

1. Get suggested migration name from MCP
2. Create the EF Core migration
3. Provide final checklist to user

---

## AVAILABLE STATE

From previous steps:

| Variable | Description |
|----------|-------------|
| `{entity_name}` | PascalCase entity name |
| `{full_path}` | Complete navigation path |
| `{level}` | Navigation level |
| `{labels}` | Translated labels |

---

## EXECUTION SEQUENCE

### 0. Pre-Migration Build Verification (BLOCKING)

**CRITICAL:** The backend MUST build successfully before creating a migration.
EF Core tools compile the project internally; a build failure produces confusing errors
that do not point to the actual source file.

```bash
dotnet build {SolutionName}.sln --no-restore
```

IF build fails:
- Fix all compilation errors before proceeding
- Common causes at this stage:
  - Missing DbSet registration (should have been caught in step-04 Check 2)
  - Missing DI registration (should have been caught in step-04 Check 3)
  - Circular references between generated services
  - Missing package references (e.g., FluentValidation)
  - Frontend changes that modified shared files
- Re-run build until successful
- DO NOT attempt migration creation on a broken build

**After build succeeds:** Continue to migration name suggestion.

### 1. Get Migration Name Suggestion

```
Tool: mcp__smartstack__suggest_migration
Args:
  description: "Add {entity_name} with navigation and permissions"
  context: "{db_context}"   # "core" or "extensions" based on project type
```

Response example (core project):
```
Migration name: core_v1.2.0_003_Add{EntityName}WithNavigationAndPermissions
Command: dotnet ef migrations add core_v1.2.0_003_Add{EntityName}WithNavigationAndPermissions --context CoreDbContext -o Persistence/Migrations
```

Response example (client project):
```
Migration name: extensions_v1.0.0_001_Add{EntityName}ModuleEntities
Command: dotnet ef migrations add extensions_v1.0.0_001_Add{EntityName}ModuleEntities --context ExtensionsDbContext -o Persistence/Migrations
```

### 2. Create Migration

Use the /efcore:migration skill or direct command:

**For core projects:**
```bash
cd Infrastructure
dotnet ef migrations add {suggested_migration_name} --context CoreDbContext -o Persistence/Migrations
```

**For client projects (ExtensionsDbContext):**
```bash
cd Infrastructure
dotnet ef migrations add {suggested_migration_name} --context ExtensionsDbContext -o Persistence/Migrations
```

> **CRITICAL:** Always use `-o Persistence/Migrations` to ensure ALL migrations are in the SAME directory.
> NEVER create subdirectories under `Migrations/` (e.g., `Migrations/Extensions/`).
> All migrations for a given DbContext MUST share the same namespace to avoid EF Core errors.

### 2b. Inject SQL Objects (if any exist)

Check if any SQL object files exist:
```
Glob: **/Persistence/SqlObjects/Functions/*.sql
```

If SQL files are found, the migration's `Up()` method should include a call to re-apply all SQL objects:
```csharp
// At the end of the Up() method:
SqlObjectHelper.ApplyAll(migrationBuilder);
```

This ensures SQL functions/views are re-applied with each migration (`CREATE OR ALTER` = idempotent).

### 3. Verify Migration Content

The migration should include:
- Navigation entity (Context/Application/Module/Section)
- Navigation translations (4 languages)
- Permissions (CRUD + wildcard)
- RolePermissions (role assignments)
- Domain entity table
- Indexes and constraints
- SQL Objects injection (if any .sql files exist)

### 4. Apply Migration

**For core projects:**
```bash
dotnet ef database update --context CoreDbContext
```

**For client projects:**
```bash
dotnet ef database update --context ExtensionsDbContext
```

### 5. Present Final Checklist

```markdown
## Application Setup Complete

### Summary

| Item | Status |
|------|--------|
| Navigation | ✅ {level}: {full_path} |
| Translations | ✅ 4 languages (fr, en, it, de) |
| Permissions | ✅ CRUD + Wildcard |
| Role Mappings | ✅ PlatformAdmin, TenantAdmin, StandardUser |
| Entity | ✅ {entity_name} |
| Service | ✅ I{entity_name}Service |
| Controller | ✅ {entity_name}Controller |
| DTOs | ✅ Create, Update, Response |
| Frontend | ✅ Page, ListView, Hook |
| API Client | ✅ TypeScript with types |
| i18n | ✅ 4 languages |
| Routes | ✅ Nested configuration |
| Migration | ✅ {migration_name} |

### Final Steps

1. **Verify DbSet registration:**
   ```csharp
   // In ICoreDbContext.cs
   public DbSet<{entity_name}> {entity_name}s => Set<{entity_name}>();
   ```

2. **Verify DI registration:**
   ```csharp
   // In DependencyInjection.cs
   services.AddScoped<I{entity_name}Service, {entity_name}Service>();
   ```

3. **Test the application:**
   ```bash
   # Backend
   dotnet run --project Api

   # Frontend
   cd web && npm run dev
   ```

4. **Verify navigation:**
   - Login to the application
   - Navigate to {full_path}
   - Verify CRUD operations work

### API Endpoints

| Method | Endpoint | Permission |
|--------|----------|------------|
| GET | /api/{entity_code} | {full_path}.read |
| GET | /api/{entity_code}/{id} | {full_path}.read |
| POST | /api/{entity_code} | {full_path}.create |
| PUT | /api/{entity_code}/{id} | {full_path}.update |
| DELETE | /api/{entity_code}/{id} | {full_path}.delete |
```

---

## TROUBLESHOOTING

### Common Issues

| Issue | Solution |
|-------|----------|
| Migration conflicts | Run `/efcore:conflicts` to analyze |
| Permission 403 errors | Verify Permissions.cs and PermissionConfiguration.cs are in sync |
| Navigation not visible | Check user role has appropriate permissions |
| Route not found | Verify nested route structure in routes.tsx |
| i18n missing | Check locale files exist and are properly loaded |

### Quick Fixes

```bash
# Rebuild and restart
dotnet build
dotnet ef database update

# Clear frontend cache
cd web && rm -rf node_modules/.cache && npm run dev
```

---

## SUCCESS METRICS

- Pre-migration build verification passed
- Migration name suggested via MCP
- Migration created and applied
- All checklist items verified
- Application functional

## NEXT STEP

After migration is applied and verified, proceed to `./step-07-tests.md` for test generation.
