---
description: Completely reset database (Drop + Recreate + Migrations)
agent: efcore-db-reset
model: sonnet
---

# EF Core Database Reset

Drops and recreates the database, then applies all migrations using EF Core CLI only.

**WARNING: This command DELETES all data!**

> **CLAUDE INSTRUCTION:** The `AskUserQuestion({...})` blocks are instructions to use the `AskUserQuestion` tool in an **interactive** manner. You MUST execute the tool with these parameters to get the user's response BEFORE continuing.

---

## RÈGLES DE CONFORMITÉ (OBLIGATOIRE)

> **INTERDIT - Violations CLAUDE.md:**
> - ❌ Utilisation de `sqlcmd` avec SQL brut
> - ❌ Scripts SQL (.sql files) dans le repository
> - ❌ Commandes SQL directes pour backup/restore
>
> **OBLIGATOIRE - Méthodes autorisées:**
> - ✅ `dotnet ef database drop` pour supprimer
> - ✅ `dotnet ef database update` pour recréer
> - ✅ Backup via outils externes (SQL Server Management Studio, Azure)
>
> **Contact support:** support@atlshub.ch

---

## STEP 0: Verification environnement et connexion (CRITIQUE)

> **Include:** `_env-check.md` - TOUTES les etapes car commande destructive

### 0.1 Detecter les fichiers appsettings

```bash
# Scanner les fichiers appsettings
API_DIR=$(find . -type d -name "*.Api" | head -1)
[ -z "$API_DIR" ] && API_DIR="src/SmartStack.Api"

echo "FICHIERS APPSETTINGS DISPONIBLES:"
find "$API_DIR" -maxdepth 1 -name "appsettings*.json" 2>/dev/null | while read f; do
  echo "  - $(basename $f)"
done
```

### 0.2 Selectionner l'environnement

```bash
# Priorite: --env flag > appsettings.Local.json > erreur
ENV_FLAG="${1#--env=}"

if [ -n "$ENV_FLAG" ] && [ "$ENV_FLAG" != "$1" ]; then
  SELECTED_ENV="appsettings.${ENV_FLAG}.json"
elif [ -f "$API_DIR/appsettings.Local.json" ]; then
  SELECTED_ENV="appsettings.Local.json"
else
  echo "ERROR: Aucun fichier appsettings trouve"
  echo "  Creez appsettings.Local.json ou utilisez --env {Environment}"
  exit 1
fi

echo ""
echo "ENVIRONNEMENT SELECTIONNE: $SELECTED_ENV"
```

### 0.3 Extraire et afficher la connexion

```bash
# Extraire connection string
CONNECTION_STRING=$(powershell -Command "
  \$json = Get-Content '$API_DIR/$SELECTED_ENV' | ConvertFrom-Json
  \$json.ConnectionStrings.DefaultConnection
")

DATABASE_NAME=$(echo "$CONNECTION_STRING" | grep -oP 'Database=\K[^;]+')
SERVER_NAME=$(echo "$CONNECTION_STRING" | grep -oP 'Server=\K[^;]+')
CONNECTION_MASKED=$(echo "$CONNECTION_STRING" | sed 's/Password=[^;]*/Password=****/g')
```

### 0.4 Afficher le WARNING avec details de la base

```
================================================================================
              EF CORE - DATABASE RESET (OPERATION DESTRUCTIVE)
================================================================================

ENVIRONNEMENT: {SELECTED_ENV}

BASE DE DONNEES QUI SERA SUPPRIMEE:
  Server:   {SERVER_NAME}
  Database: {DATABASE_NAME}
  String:   {CONNECTION_MASKED}

================================================================================
```

### 0.5 Protection Production (BLOQUANT)

```bash
# Bloquer si Production detecte
if [[ "$SELECTED_ENV" == *"Production"* ]]; then
  echo "================================================================================
                         BLOQUE - ENVIRONNEMENT PRODUCTION
================================================================================

ERREUR: Reset interdit en environnement Production

Cette commande est bloquee pour proteger les donnees de production.

OPTIONS:
1. Utilisez appsettings.Local.json (defaut, recommande)
2. Utilisez --env Development ou --env Staging

Contact: support@atlshub.ch

================================================================================"
  exit 1
fi
```

---

## STEP 1: Confirmation obligatoire (avec nom de la base)

> **CRITIQUE:** L'utilisateur doit voir exactement quelle base sera supprimee.

```javascript
AskUserQuestion({
  questions: [{
    question: "DANGER: Supprimer DEFINITIVEMENT la base '" + DATABASE_NAME + "' sur " + SERVER_NAME + "? TOUTES LES DONNEES SERONT PERDUES!",
    header: "Reset DB",
    options: [
      { label: "Oui, supprimer " + DATABASE_NAME, description: "Drop + Recreate (DATA LOSS IRREVERSIBLE)" },
      { label: "Non, annuler", description: "Conserver la base actuelle" }
    ],
    multiSelect: false
  }]
})
```

**If No → Stop immediately**

---

## STEP 2: Detecter les projets EF Core

```bash
# Detect EF Core projects
STARTUP_PROJECT=$(find . -name "*.Api.csproj" -o -name "*Web.csproj" | head -1)
INFRA_PROJECT=$(find . -name "*Infrastructure.csproj" | head -1)

if [ -z "$INFRA_PROJECT" ]; then
  INFRA_PROJECT=$(find . -name "*.csproj" -exec grep -l "Microsoft.EntityFrameworkCore" {} \; | head -1)
fi

echo "Startup project: $STARTUP_PROJECT"
echo "Infrastructure project: $INFRA_PROJECT"
```

---

## STEP 3: Backup recommendation

```javascript
AskUserQuestion({
  questions: [{
    question: "Do you need to backup data before deletion?",
    header: "Backup",
    options: [
      { label: "No backup needed", description: "Development data only - proceed" },
      { label: "Manual backup first", description: "I'll backup via SSMS/Azure Portal" }
    ],
    multiSelect: false
  }]
})
```

**If manual backup:**

```
================================================================================
                         BACKUP INSTRUCTIONS
================================================================================

Pour sauvegarder votre base de données AVANT le reset:

OPTION 1 - SQL Server Management Studio (SSMS):
  1. Connectez-vous à votre serveur
  2. Clic droit sur la DB → Tasks → Back Up...
  3. Sélectionnez destination et lancez

OPTION 2 - Azure Portal (si Azure SQL):
  1. Azure Portal → Votre DB → Export
  2. Configurez le storage account
  3. Lancez l'export

OPTION 3 - Azure Data Studio:
  1. Connectez-vous → Clic droit DB → Backup

Une fois le backup effectué, relancez /efcore:db-reset

================================================================================
```

**Stop and wait for user to complete backup manually**

---

## STEP 4: Check migration state BEFORE drop

```bash
echo "Checking migration state..."

# List migrations in codebase
CODE_MIGRATIONS=$(dotnet ef migrations list \
  --project "$INFRA_PROJECT" \
  --startup-project "$STARTUP_PROJECT" \
  --no-build 2>/dev/null | grep -E "^[0-9]{14}_" | wc -l)

echo "  Migrations in codebase: $CODE_MIGRATIONS"

# Try to get applied migrations from database (may fail if DB doesn't exist)
APPLIED_MIGRATIONS=$(dotnet ef migrations list \
  --project "$INFRA_PROJECT" \
  --startup-project "$STARTUP_PROJECT" \
  --no-build 2>/dev/null | grep -E "^\s*[0-9]{14}_.*\(Applied\)" | wc -l)

echo "  Migrations applied in DB: $APPLIED_MIGRATIONS"

# List migration names for display
echo ""
echo "Migrations in codebase:"
dotnet ef migrations list \
  --project "$INFRA_PROJECT" \
  --startup-project "$STARTUP_PROJECT" \
  --no-build 2>/dev/null | grep -E "^[0-9]{14}_" | head -20
```

---

## STEP 5: Confirm migration reset strategy

> **IMPORTANT:** If migrations were squashed (fewer migrations in code than previously applied),
> applying all migrations will create a fresh database with the NEW migration history.

```javascript
AskUserQuestion({
  questions: [{
    question: "How should we handle migrations after database reset?",
    header: "Migrations",
    options: [
      { label: "Apply current migrations", description: "Use migrations currently in codebase (recommended after squash)" },
      { label: "Cancel reset", description: "Stop and review migration state first" }
    ],
    multiSelect: false
  }]
})
```

**If "Cancel reset" → Stop immediately and suggest:**

```
================================================================================
                    RESET CANCELLED - REVIEW MIGRATIONS
================================================================================

Pour vérifier l'état des migrations:

  /efcore:db-status     → Voir les migrations appliquées vs disponibles
  /efcore:scan          → Scanner les migrations sur toutes les branches

Si des migrations ont été squashées:
  - Les anciennes migrations n'existent plus dans le code
  - Le reset appliquera uniquement les nouvelles migrations
  - C'est le comportement ATTENDU après un squash

Si vous voulez restaurer d'anciennes migrations:
  - Vérifiez l'historique git: git log --oneline -- "**/Migrations/"
  - Restaurez les fichiers: git checkout <commit> -- path/to/Migrations/

================================================================================
```

---

## STEP 6: Drop database

```bash
echo "Dropping database..."

# Use EF Core CLI only (NO sqlcmd)
dotnet ef database drop \
  --project "$INFRA_PROJECT" \
  --startup-project "$STARTUP_PROJECT" \
  --force

if [ $? -eq 0 ]; then
  echo "  Database dropped successfully"
else
  echo "  WARNING: Drop command returned error (database may not exist)"
fi
```

---

## STEP 7: Recreate and apply migrations

```bash
echo "Applying all migrations..."

# Apply all migrations (creates database if missing)
dotnet ef database update \
  --project "$INFRA_PROJECT" \
  --startup-project "$STARTUP_PROJECT" \
  --verbose

if [ $? -ne 0 ]; then
  echo "ERROR: Failed to apply migrations"
  exit 1
fi

echo "  Database recreated with all migrations"
```

---

## STEP 8: Optional seed

```javascript
AskUserQuestion({
  questions: [{
    question: "Populate database with test data (via HasData)?",
    header: "Seed",
    options: [
      { label: "Yes (recommended)", description: "Apply HasData seed from migrations" },
      { label: "No", description: "Empty database" }
    ],
    multiSelect: false
  }]
})
```

**If yes:**

```bash
# HasData is already applied via migrations
# If additional seeding needed, use Seeder class
if grep -rq "IDataSeeder\|class.*Seeder" . --include="*.cs" 2>/dev/null; then
  echo "Executing DataSeeder..."
  dotnet run --project "$STARTUP_PROJECT" -- --seed
else
  echo "  HasData() seed already applied via migrations"
fi
```

---

## STEP 9: Verification

```bash
echo "Verifying database..."

# Check migrations status
dotnet ef migrations list \
  --project "$INFRA_PROJECT" \
  --startup-project "$STARTUP_PROJECT" \
  --no-build 2>/dev/null | tail -10

echo ""
echo "  Use /efcore:db-status for detailed status"
```

---

## STEP 10: Summary

```
================================================================================
                         DATABASE RESET COMPLETE
================================================================================

✓ Old database deleted (via dotnet ef database drop)
✓ New database created (via dotnet ef database update)
✓ All migrations applied
{✓ HasData seed applied | ○ Empty database}

COMPLIANT: ✓ EF Core CLI only (no raw SQL)

NEXT COMMANDS:
  /efcore:db-status  → Check status
  /efcore:db-seed    → Additional seeding (if needed)
  dotnet run         → Launch application

================================================================================
```

---

## Options

| Option | Description |
|--------|-------------|
| `--env {name}` | Utiliser appsettings.{name}.json (ex: --env Development) |

## Security

| Protection | Description |
|------------|-------------|
| Env Display | Affiche la base de donnees AVANT confirmation |
| Confirmation | Demande explicite avec le NOM de la base |
| Production Block | Bloque si appsettings.Production.json detecte |
| Migration Check | Displays migration state and asks before applying |
| EF Core Only | No raw SQL commands - uses dotnet ef CLI |
| Manual Backup | User directed to SSMS/Azure for backups |

---

## Support

> **Questions ou problèmes avec le reset EF Core?**
>
> 📧 **support@atlshub.ch**
