Index rapide des commandes Quick Command Index

Acces direct a toutes les commandes EF Core. Cliquez sur une commande pour voir sa documentation complete.

Direct access to all EF Core commands. Click a command to see its full documentation.

Commande Command Description Agent Risque Risk
/efcore migration Creer/recreer la migration unique pour la branche Create/recreate the unique migration for the branch efcore-migration MEDIUM
/efcore db-status Afficher l'etat des migrations et de la DB Show migrations and database status efcore-db-status READ
/efcore db-deploy Appliquer les migrations en attente Apply pending migrations efcore-db-deploy MEDIUM
/efcore db-seed Peupler la base avec des donnees de test Populate database with test data efcore-db-seed MEDIUM
/efcore db-reset Supprimer et recreer la base (DESTRUCTIF) Drop and recreate database (DESTRUCTIVE) efcore-db-reset HIGH
/efcore scan Scanner les migrations sur toutes les branches Scan migrations across all branches efcore-scan READ
/efcore conflicts Analyser les conflits avant merge (BLOQUANT) Analyze conflicts before merge (BLOCKING) efcore-conflicts READ
/efcore rebase-snapshot Rebaser ModelSnapshot sur develop Rebase ModelSnapshot on develop efcore-rebase-snapshot MEDIUM
/efcore squash Fusionner plusieurs migrations en une seule Merge multiple migrations into one efcore-squash HIGH
💡
Workflow typique
Typical Workflow

/efcore db-status/efcore migration/efcore db-deploy/gitflow commit

/efcore db-status/efcore migration/efcore db-deploy/gitflow commit

Introduction

Entity Framework Core (EF Core) est l'ORM officiel de Microsoft pour .NET. SmartStack CLI integre une gestion avancee des migrations EF Core dans le workflow GitFlow, incluant la detection de conflits, la validation des migrations et la generation de scripts SQL idempotents.

Entity Framework Core (EF Core) is Microsoft's official ORM for .NET. SmartStack CLI integrates advanced EF Core migration management into the GitFlow workflow, including conflict detection, migration validation, and idempotent SQL script generation.

💡
Integration automatique
Automatic Integration

SmartStack CLI detecte automatiquement les projets .NET utilisant EF Core lors de l'initialisation avec /gitflow init.

SmartStack CLI automatically detects .NET projects using EF Core during initialization with /gitflow init.

Fonctionnalites principales

Key Features

🗄
1 Migration par Feature
1 Migration per Feature
Regle d'or
Golden rule

Chaque branche feature/hotfix a exactement une migration. Si des changements sont necessaires, elle est supprimee et recreee.

Each feature/hotfix branch has exactly one migration. If changes are needed, it's deleted and recreated.

🔀
Cross-Branch
Detection de conflits
Conflict detection

Analyse des ModelSnapshots sur toutes les branches actives pour prevenir les conflits avant le merge.

Analyze ModelSnapshots across all active branches to prevent conflicts before merge.

🔒
Securite
Safety
Operations protegees
Protected operations

Backup automatique avant operations destructives. Detection des DropTable, DropColumn, DeleteData.

Automatic backup before destructive operations. Detection of DropTable, DropColumn, DeleteData.

Comprendre EF Core et les Migrations Understanding EF Core and Migrations

Qu'est-ce qu'une Migration ?

What is a Migration?

Une migration EF Core represente un changement incrementiel du schema de votre base de donnees. Elle capture les differences entre l'etat actuel de vos entites C# et l'etat precedent.

An EF Core migration represents an incremental change to your database schema. It captures the differences between the current state of your C# entities and the previous state.

Les 3 fichiers d'une Migration

The 3 Files of a Migration

Une migration EF Core valide comprend 3 fichiers :

A valid EF Core migration includes 3 files:

Fichier / File Description Description Role Role
{Timestamp}_{Name}.cs Migration principale Main migration Contient Up() et Down() Contains Up() and Down()
{Timestamp}_{Name}.Designer.cs Metadonnees Metadata Snapshot du modele au moment de la creation Model snapshot at creation time
{Context}ModelSnapshot.cs Etat actuel Current state Modele complet - source de conflits! Full model - conflict source!
Migration Structure (3 Files) {Name}.cs Up() → Apply changes Down() → Rollback changes {Name}.Designer.cs Metadata → MigrationId → ProductVersion → Model snapshot at time ModelSnapshot.cs Current State → Full model definition → All entities & relations → ⚠️ Conflict source 1 Model Change Edit your DbContext entities 2 Add Migration dotnet ef migrations add 3 3 Files Generated Commit all together! ⚠️ ModelSnapshot.cs is regenerated on EVERY migration - source of merge conflicts!
Migrations/
├── 20240101120000_InitialCreate.cs
├── 20240101120000_InitialCreate.Designer.cs
├── 20240115150000_AddUserTable.cs
├── 20240115150000_AddUserTable.Designer.cs
└── ApplicationDbContextModelSnapshot.cs  ← Fichier critique
ModelSnapshot - Le point de conflit

Le fichier ModelSnapshot.cs represente l'etat actuel du modele. Il est regenere a chaque nouvelle migration. C'est la source principale de conflits lors des merges entre branches.

The ModelSnapshot.cs file represents the current model state. It's regenerated on every new migration. It's the main source of conflicts when merging branches.

Architecture Dual DbContext Dual DbContext Architecture

SmartStack utilise deux DbContexts separes avec des historiques de migration independants. Cette architecture permet de separer le code plateforme (SmartStack) du code client.

SmartStack uses two separate DbContexts with independent migration histories. This architecture separates platform code (SmartStack) from client code.

Context DbContext Schema History Table Utilisation Use Case
core CoreDbContext core core.__EFMigrationsHistory Entites plateforme SmartStack (User, Role, Navigation, etc.) SmartStack platform entities (User, Role, Navigation, etc.)
extensions ExtensionsDbContext extensions extensions.__EFMigrationsHistory Entites specifiques au client Client-specific entities

Detection automatique

Automatic Detection

Le systeme detecte automatiquement quel DbContext utiliser :

The system automatically detects which DbContext to use:

  1. Si le projet contient SmartStack.DomainCoreDbContext

    If project contains SmartStack.DomainCoreDbContext

  2. Si le projet contient un {ClientName}.Domain avec NuGet SmartStack → ExtensionsDbContext

    If project contains {ClientName}.Domain with SmartStack NuGet → ExtensionsDbContext

  3. Si ambigue → demande a l'utilisateur

    If ambiguous → asks user

Regles importantes
Important Rules
🔒 Les entites Extensions ne peuvent pas avoir de navigation properties vers les entites Core Extensions entities cannot have navigation properties to Core entities
🔗 Utilisez ICoreDataService pour acceder aux donnees Core depuis Extensions Use ICoreDataService to access Core data from Extensions
🗃 Chaque DbContext a sa propre table __EFMigrationsHistory Each DbContext has its own __EFMigrationsHistory table
🔄 Migrations appliquees dans l'ordre : Core d'abord, puis Extensions Migrations applied in order: Core first, then Extensions
# Core migrations (SmartStack platform)
dotnet ef migrations add $MCP_NAME --context CoreDbContext -o Persistence/Migrations

# Extensions migrations (Client specific)
dotnet ef migrations add $MCP_NAME --context ExtensionsDbContext -o Persistence/Migrations

# Note: $MCP_NAME is generated by mcp__smartstack__suggest_migration

La regle "1 Migration par Feature" The "1 Migration per Feature" Rule

🎯
Regle d'or
Golden Rule

Chaque branche feature/hotfix doit avoir exactement 1 seule migration. Si elle existe deja et que vous devez la modifier, supprimez-la et recreez-la.

Each feature/hotfix branch must have exactly 1 migration. If it already exists and you need to modify it, delete and recreate it.

Pourquoi cette regle ?

Why this rule?

Probleme Problem Solution avec 1 migration Solution with 1 migration
Conflits de merge sur ModelSnapshot ModelSnapshot merge conflicts 1 seul point de conflit, facile a resoudre Single conflict point, easy to resolve
Historique de migrations pollue Polluted migration history Historique propre et lisible Clean and readable history
Ordre de migrations complexe Complex migration ordering Ordre simple : 1 feature = 1 migration Simple order: 1 feature = 1 migration
Rollback difficile Difficult rollback Rollback simple de la feature entiere Simple rollback of entire feature

Pattern de nommage (MCP obligatoire)

Naming Pattern (MCP mandatory)

🔒
Nommage via MCP
Naming via MCP

Le nom de migration est toujours genere par le MCP via mcp__smartstack__suggest_migration. Ne jamais calculer le nom manuellement.

Migration name is always generated by MCP via mcp__smartstack__suggest_migration. Never calculate the name manually.

{context}_v{version}_{sequence}_{Description}
Context Version Sequence Description Nom genere (MCP) Generated name (MCP)
core 1.9.0 001 AddUserRoles core_v1.9.0_001_AddUserRoles
extensions 1.2.0 001 AddCustomFields extensions_v1.2.0_001_AddCustomFields
core 1.7.0 001 UserAuthConsolidated core_v1.7.0_001_UserAuthConsolidated

Workflow pratique

Practical Workflow

# Situation: You already have a migration and need to modify the model

# 1. Check current state
/efcore db-status

# 2. See there's already 1 migration for this branch
#    Output: "1 migration for feature/user-auth"

# 3. Create/Recreate migration (deletes old one automatically)
/efcore migration

# 4. Choose "Recreate" when prompted
# 5. Enter description (e.g., "AddRolesTable")
# 6. Apply to local DB
/efcore db-deploy

# 7. Commit
/gitflow commit

Documentation des Commandes Command Documentation

SmartStack CLI fournit 9 commandes specialisees pour gerer les migrations EF Core. Chaque commande utilise un agent dedie optimise pour sa tache.

SmartStack CLI provides 9 specialized commands for EF Core migration management. Each command uses a dedicated agent optimized for its task.

/efcore migration MEDIUM

Cette commande applique la regle d'or "1 migration par feature" : chaque branche feature ou hotfix ne doit avoir qu'une seule migration. Si vous modifiez le modele de donnees plusieurs fois pendant le developpement, la commande detecte la migration existante, la supprime, et en cree une nouvelle qui consolide tous les changements. Avant de creer, elle effectue une validation cross-branch pour detecter les conflits potentiels avec d'autres branches actives. Le nom de migration suit un pattern standardise incluant le type de branche, la version, et une description. Cette approche garantit un historique de migrations propre et evite les conflits lors des merges.

This command enforces the "1 migration per feature" golden rule: each feature or hotfix branch should have only one migration. If you modify the data model multiple times during development, the command detects the existing migration, deletes it, and creates a new one that consolidates all changes. Before creating, it performs cross-branch validation to detect potential conflicts with other active branches. The migration name follows a standardized pattern including branch type, version, and description. This approach ensures a clean migration history and prevents conflicts during merges.

Agent efcore-migration
Model sonnet
Tools Bash, Glob, Read, Edit

Workflow en 9 etapes

9-Step Workflow

1
Cross-Branch
Verifie les conflits cross-branch
2
Contexte Git
Branche, type, version
3
Detection
Trouver le .csproj EF Core
Recherche
Migration existante?
5
Decision
Creer ou Recreer
6
Description
Add, Update, Fix, Remove
7
Nommage
Pattern standardise
8
Creation
dotnet ef migrations add
9
Validation
Apercu et confirmation
1
Cross-Branch
Check cross-branch conflicts
2
Git Context
Branch, type, version
3
Detection
Find EF Core .csproj
Search
Existing migration?
5
Decision
Create or Recreate
6
Description
Add, Update, Fix, Remove
7
Naming
Standardized pattern
8
Creation
dotnet ef migrations add
9
Validation
Preview and confirm

Options

Option Description
--name {name} Forcer un nom specifique Force a specific name
--no-apply Ne pas proposer d'appliquer Don't offer to apply
--force Supprimer l'existante sans confirmation Delete existing without confirmation
--no-cross-check Desactiver validation cross-branch Disable cross-branch validation
--rebase-first Executer rebase-snapshot automatiquement si conflit Run rebase-snapshot automatically if conflict
# Usage example
/efcore migration

# With options
/efcore migration --force --no-apply
/efcore db-status READ

Cette commande de diagnostic rapide (read-only) fournit une vue complete de l'etat des migrations EF Core et de la base de donnees. Elle detecte automatiquement le fichier de configuration (appsettings.Local.json en priorite), teste la connexion a la base, et liste toutes les migrations en distinguant celles appliquees de celles en attente. Elle verifie egalement le respect de la regle "1 migration par feature" en analysant les migrations presentes sur la branche courante. Utilisez cette commande avant toute operation pour connaitre l'etat exact du systeme.

This quick diagnostic command (read-only) provides a complete view of EF Core migrations and database state. It automatically detects the configuration file (appsettings.Local.json as priority), tests database connection, and lists all migrations distinguishing applied from pending ones. It also verifies "1 migration per feature" rule compliance by analyzing migrations present on the current branch. Use this command before any operation to know the exact system state.

Agent efcore-db-status
Model haiku (fast)
Tools Bash, Glob

Informations affichees

Displayed Information

Configuration utilisee (appsettings.Local.json, etc.) Configuration used (appsettings.Local.json, etc.)
🔗 Statut de connexion a la base Database connection status
📊 Nombre de migrations (total, appliquees, en attente) Migration count (total, applied, pending)
Verification de la regle "1 migration par feature" "1 migration per feature" rule verification
🗃 Taille de la base et nombre de tables Database size and table count
================================================================================
                         EF CORE - DATABASE STATUS
================================================================================

PROJET
  Nom:           MyApp.Data
  Config:        appsettings.Local.json
  DbContext:     ApplicationDbContext

CONNEXION
  Status:        OK
  Server:        localhost
  Database:      MyAppDb

MIGRATIONS
  Total:         12
  Appliquees:    11
  En attente:    1

REGLE "1 MIGRATION PAR FEATURE"
  Branche:      feature/user-auth
  Migrations:   1 pour cette branche
  Regle respectee

================================================================================

Options

Option Description
--verbose Afficher toutes les migrations avec details Show all migrations with details
--json Sortie JSON pour scripting JSON output for scripting
--context {name} Specifier le DbContext Specify DbContext
/efcore db-deploy MEDIUM

Cette commande applique toutes les migrations en attente sur votre base de donnees locale. Elle utilise le fichier appsettings.Local.json pour obtenir la connection string, verifie d'abord qu'il y a des migrations a appliquer, puis execute dotnet ef database update. Le processus affiche les details SQL en mode verbose pour suivre les modifications appliquees. Cette commande est essentielle apres avoir cree une nouvelle migration ou apres avoir recupere des modifications d'autres developpeurs contenant des migrations.

This command applies all pending migrations to your local database. It uses appsettings.Local.json file to get the connection string, first verifies there are migrations to apply, then executes dotnet ef database update. The process displays SQL details in verbose mode to track applied modifications. This command is essential after creating a new migration or after pulling changes from other developers containing migrations.

Agent efcore-db-deploy
Model haiku (fast)
Tools Bash, Glob

Prerequis

Prerequisites

📄 appsettings.Local.json configure
🖥 SQL Server accessible SQL Server accessible
🔄 Migrations en attente Pending migrations
# Deploy migrations
/efcore db-deploy

# Equivalent to:
dotnet ef database update --verbose

Options

Option Description
--verbose Afficher les details SQL Show SQL details
--connection "..." Override connection string Override connection string
--context {name} Specifier le DbContext si multiple Specify DbContext if multiple
/efcore db-seed MEDIUM

Cette commande peuple la base de donnees avec des donnees de test ou initiales pour le developpement local. Elle detecte automatiquement les methodes de seeding disponibles dans le projet : classe Seeder dediee, methode HasData() dans le DbContext, script SQL seed.sql, ou argument CLI --seed. Elle vous propose ensuite de choisir la methode a utiliser. Ideale apres un /efcore db-reset ou pour initialiser un nouvel environnement de developpement avec des donnees coherentes.

This command populates the database with test or initial data for local development. It automatically detects available seeding methods in the project: dedicated Seeder class, HasData() method in DbContext, seed.sql SQL script, or CLI --seed argument. It then offers you to choose which method to use. Ideal after /efcore db-reset or to initialize a new development environment with consistent data.

Agent efcore-db-seed
Model haiku (fast)
Tools Bash, Glob, Read

Methodes de seeding detectees

Detected Seeding Methods

Methode Method Detection Detection Execution Execution
Seeder Class class.*Seeder dotnet run -- --seed
HasData() .HasData( Via migrations Via migrations
Script SQL ./scripts/seed.sql sqlcmd -i seed.sql
CLI --seed --seed in Program.cs dotnet run -- --seed
# Execute seeding
/efcore db-seed

# The agent automatically detects available methods
# and offers you a choice
/efcore db-reset HIGH - DESTRUCTIVE

Cette commande destructive remet la base de donnees a zero en la supprimant completement puis en la recreant avec toutes les migrations. Elle est protegee par plusieurs securites : confirmation obligatoire, proposition de backup avant suppression, blocage si l'environnement est detecte comme Production. Apres la recreation, elle propose optionnellement d'executer le seeding. Utilisez cette commande quand vous avez besoin d'un environnement de developpement completement propre, par exemple apres des modifications majeures du schema ou pour tester le processus complet de migrations.

This destructive command resets the database to zero by completely dropping it then recreating it with all migrations. It's protected by several safeguards: mandatory confirmation, backup offer before deletion, blocking if environment is detected as Production. After recreation, it optionally offers to run seeding. Use this command when you need a completely clean development environment, for example after major schema changes or to test the complete migration process.

ATTENTION: Cette commande SUPPRIME toutes les donnees!

WARNING: This command DELETES all data!

Agent efcore-db-reset
Model sonnet (securite)
Tools Bash, Glob, Read

Protections de securite

Safety Protections

🔒 Confirmation obligatoire - Dialogue bloquant Mandatory confirmation - Blocking dialog
💾 Backup propose - Avant suppression Backup offered - Before deletion
🚫 Check environnement - Bloque si Production Environment check - Blocks if Production
🌱 Seed optionnel - Apres recreation Optional seed - After recreation
# Complete database reset
/efcore db-reset

# Workflow:
# 1. Mandatory confirmation
# 2. Optional backup (recommended)
# 3. DROP DATABASE
# 4. CREATE DATABASE (via migrations)
# 5. Optional seed
/efcore scan READ

Cette commande read-only scanne tous les worktrees actifs (main, develop, et toutes les branches feature/hotfix) pour cartographier les migrations EF Core presentes. Elle compare chaque ModelSnapshot avec celui de develop pour calculer un niveau de risque : NONE (identique), LOW (tables differentes), MEDIUM (FK vers memes tables), HIGH (meme table modifiee), ou CRITICAL (meme colonne). Le resultat inclut un ordre de merge recommande basant sur ces risques. Executez cette commande avant de commencer une integration pour avoir une vue globale de l'etat des migrations dans l'equipe.

This read-only command scans all active worktrees (main, develop, and all feature/hotfix branches) to map present EF Core migrations. It compares each ModelSnapshot with develop's to calculate a risk level: NONE (identical), LOW (different tables), MEDIUM (FK to same tables), HIGH (same table modified), or CRITICAL (same column). The result includes a recommended merge order based on these risks. Run this command before starting an integration to get a global view of migration state across the team.

Agent efcore-scan
Model sonnet
Tools Bash, Glob, Read

Niveaux de risque

Risk Levels

Niveau Level Signification Meaning Action
NONE Snapshot = develop Snapshot = develop Merge direct
LOW Tables differentes Different tables Merge OK
MEDIUM FK vers memes tables FK to same tables Attention a l'ordre Order matters
HIGH Meme table modifiee Same table modified Rebase requis Rebase required
CRITICAL Meme colonne modifiee Same column modified Intervention manuelle Manual intervention
================================================================================
                    EF CORE CROSS-BRANCH SCAN
================================================================================

WORKTREES DETECTES (5)
  main/                    [main]
  develop/                 [develop]
  features/user-auth/      [feature/user-auth]
  features/add-products/   [feature/add-products]
  hotfixes/login-fix/      [hotfix/login-fix]

MIGRATIONS PAR BRANCHE
  develop               | 12 migrations | Snapshot: a1b2c3d4 (REFERENCE)
  feature/user-auth     | 13 migrations | Snapshot: e5f6g7h8
  feature/add-products  | 13 migrations | Snapshot: i9j0k1l2
  hotfix/login-fix      | 12 migrations | Snapshot: a1b2c3d4

ANALYSE DES RISQUES
  feature/user-auth     : LOW      (tables differentes)
  feature/add-products  : MEDIUM   (FK vers meme table)
  hotfix/login-fix      : NONE     (snapshot = develop)

ORDRE DE MERGE RECOMMANDE
  1. hotfix/login-fix      (NONE - merge direct)
  2. feature/user-auth     (LOW - merge OK)
  3. feature/add-products  (MEDIUM - apres user-auth)

================================================================================

Options

Option Description
--json Output en format JSON pour CI/CD JSON output for CI/CD
--branch {name} Scanner une branche specifique Scan a specific branch
--verbose Afficher les details des differences Show difference details
--no-recommend Ne pas afficher les recommandations Don't show recommendations
/efcore conflicts READ - BLOCKING

Cette commande analyse si la branche courante peut etre mergee dans develop sans conflit de migration EF Core. Elle compare le ModelSnapshot local avec celui de develop et des autres branches actives pour detecter les modifications qui se chevauchent : tables communes modifiees, colonnes identiques ajoutees, ou FK vers les memes entites. Si un conflit HIGH ou CRITICAL est detecte, la commande est BLOQUANTE et retourne un code d'erreur, empechant le merge. Elle recommande alors d'utiliser /efcore rebase-snapshot pour resoudre le conflit avant de continuer.

This command analyzes if the current branch can be merged into develop without EF Core migration conflict. It compares local ModelSnapshot with develop's and other active branches to detect overlapping modifications: common tables modified, identical columns added, or FK to same entities. If a HIGH or CRITICAL conflict is detected, the command is BLOCKING and returns an error code, preventing merge. It then recommends using /efcore rebase-snapshot to resolve the conflict before continuing.

Agent efcore-conflicts
Model sonnet
Tools Bash, Glob, Read

Exit Codes

Exit Codes

Code Signification Meaning
0 Aucun conflit ou conflit mineur No conflict or minor conflict
1 Conflit detecte - merge bloque Conflict detected - merge blocked
2 Erreur technique Technical error
# Check conflicts before merge
/efcore conflicts

# If conflict detected:
# → /efcore rebase-snapshot (recommended)
# → /efcore conflicts --force (not recommended)

Options

Option Description
--force Ignorer le conflit (non recommande) Ignore conflict (not recommended)
--verbose Afficher les differences detaillees Show detailed differences
--json Output JSON pour CI/CD JSON output for CI/CD
--target {branch} Comparer avec une autre branche que develop Compare with branch other than develop
/efcore rebase-snapshot MEDIUM

Cette commande resout les conflits ModelSnapshot detectes par /efcore conflicts en resynchronisant votre branche avec develop. Elle commence par creer un backup automatique de vos migrations, identifie les migrations specifiques a votre branche, remplace le ModelSnapshot par la version de develop, supprime vos migrations de branche, puis regenere une nouvelle migration consolidee qui inclut tous vos changements mais base sur le snapshot actuel de develop. En cas d'echec du build, elle peut restaurer automatiquement depuis le backup. C'est la solution recommandee quand un conflit HIGH est detecte.

This command resolves ModelSnapshot conflicts detected by /efcore conflicts by resynchronizing your branch with develop. It starts by creating an automatic backup of your migrations, identifies branch-specific migrations, replaces ModelSnapshot with develop's version, deletes your branch migrations, then regenerates a new consolidated migration that includes all your changes but based on develop's current snapshot. On build failure, it can automatically restore from backup. This is the recommended solution when a HIGH conflict is detected.

Agent efcore-rebase-snapshot
Model sonnet
Tools Bash, Glob, Read, Edit

Workflow en 8 etapes

8-Step Workflow

1
Prerequis
Branche GitFlow, directory propre
2
Backup
Sauvegarde automatique
Identification
Migrations branche vs develop
4
Reset Snapshot
Checkout depuis develop
5
Suppression
Anciennes migrations
6
Regeneration
Migration consolidee
7
Validation
Build + script SQL
8
Resume
Prochaines etapes
1
Prerequisites
GitFlow branch, clean directory
2
Backup
Automatic backup
Identification
Branch migrations vs develop
4
Reset Snapshot
Checkout from develop
5
Deletion
Old migrations
6
Regeneration
Consolidated migration
7
Validation
Build + SQL script
8
Summary
Next steps

Quand utiliser

When to use

Situation Action
/efcore conflicts retourne HIGH Utiliser rebase-snapshot Use rebase-snapshot
Merge conflit sur ModelSnapshot Merge conflict on ModelSnapshot Utiliser rebase-snapshot Use rebase-snapshot
Plusieurs migrations a consolider Multiple migrations to consolidate Utiliser rebase-snapshot Use rebase-snapshot
Migration cassee Broken migration Utiliser rebase-snapshot Use rebase-snapshot

Options

Option Description
--no-backup Ne pas creer de backup (dangereux) Don't create backup (dangerous)
--name {name} Forcer un nom de migration Force migration name
--dry-run Afficher ce qui serait fait Show what would be done
/efcore squash HIGH - DESTRUCTIVE

Cette commande destructive consolide toutes les migrations existantes en une seule migration propre pour les releases. Elle est utilisee typiquement avant de creer une release pour avoir un historique de migrations clean en production. Le processus cree un backup complet (migrations + script SQL du schema actuel), supprime toutes les migrations, genere une migration unique representant l'etat final du schema, puis genere un script SQL idempotent. Important : si des migrations sont deja appliquees en production, utilisez le script SQL genere plutot que la nouvelle migration pour eviter les conflits d'historique.

This destructive command consolidates all existing migrations into a single clean migration for releases. It's typically used before creating a release to have a clean migration history in production. The process creates a full backup (migrations + SQL script of current schema), deletes all migrations, generates a single migration representing the final schema state, then generates an idempotent SQL script. Important: if migrations are already applied in production, use the generated SQL script rather than the new migration to avoid history conflicts.

ATTENTION: L'historique des migrations sera perdu!

WARNING: Migration history will be lost!

Agent efcore-squash
Model sonnet
Tools Bash, Glob, Read

Quand utiliser Squash

When to use Squash

Situation Squash ?
Avant release Before release OUI - nettoyer l'historique YES - clean history
Apres merge de plusieurs features After merging multiple features OUI - consolider YES - consolidate
En production In production NON - utiliser scripts SQL NO - use SQL scripts
Branche feature en cours Feature branch in progress ATTENTION - preferer rebase-snapshot CAUTION - prefer rebase-snapshot

Options

Option Description
--no-backup Ne pas creer de backup (dangereux) Don't create backup (dangerous)
--no-script Ne pas generer de script SQL Don't generate SQL script
--name {name} Forcer un nom de migration Force migration name
--keep-snapshot Garder le ModelSnapshot actuel Keep current ModelSnapshot
--dry-run Afficher sans executer Show without executing

Cross-Branch

🌟
New Feature

Nouvelles commandes pour gerer les migrations entre plusieurs branches en parallele avec les worktrees GitFlow.

New commands to manage migrations across multiple branches in parallel with GitFlow worktrees.

Avec les worktrees GitFlow, plusieurs features peuvent etre developpees simultanement. Le systeme cross-branch previent les conflits de ModelSnapshot avant qu'ils ne se produisent.

With GitFlow worktrees, multiple features can be developed simultaneously. The cross-branch system prevents ModelSnapshot conflicts before they occur.

Workflow Cross-Branch

Cross-Branch Workflow

# 1. Scan all active branches
/efcore scan

# 2. Check conflicts before creating a migration
/efcore conflicts

# 3. If conflict detected, rebase on develop
/efcore rebase-snapshot

# 4. Create migration (automatic cross-branch validation)
/efcore migration

Configuration

{
  "efcore": {
    "crossBranch": {
      "enabled": true,
      "scanOnMigrationCreate": true,
      "blockOnConflict": true,
      "cacheExpiry": 300
    }
  }
}
Option Description Defaut Default
enabled Activer la validation cross-branch Enable cross-branch validation true
scanOnMigrationCreate Scanner avant /efcore migration Scan before /efcore migration true
blockOnConflict Bloquer si conflit detecte Block if conflict detected true
cacheExpiry Duree de cache du scan (secondes) Scan cache duration (seconds) 300

Bonnes pratiques Best Practices

Toujours commiter les 3 fichiers ensemble Always commit all 3 files together

Ne jamais commiter une migration incomplete. /gitflow commit valide automatiquement la presence des 3 fichiers.

Never commit an incomplete migration. /gitflow commit automatically validates the presence of all 3 files.

Nommer les migrations de maniere descriptive Name migrations descriptively

# Bon / Good
dotnet ef migrations add AddUserEmailIndex
dotnet ef migrations add CreateOrdersTable
dotnet ef migrations add AddPaymentStatusToOrders

# Mauvais / Bad
dotnet ef migrations add Migration1
dotnet ef migrations add Fix
dotnet ef migrations add Update

Verifier les operations destructives Check destructive operations

/gitflow commit detecte automatiquement et alerte sur les operations suivantes :

/gitflow commit automatically detects and alerts on the following operations:

Operation Risque Risk Niveau Level
DropTable Suppression de table entiere Entire table deletion CRITICAL
DropColumn Perte de donnees de colonne Column data loss CRITICAL
DeleteData Suppression de lignes Row deletion CRITICAL
DropForeignKey Casse l'integrite referentielle Breaks referential integrity HIGH
DropIndex Impact sur les performances Performance impact MEDIUM

Generer des scripts SQL idempotents pour la production Generate idempotent SQL scripts for production

# Generate an idempotent SQL script
dotnet ef migrations script --idempotent -o ./scripts/migrations/v1.2.0.sql

# The script checks if each migration has already been applied
# before executing it, making it safe for re-execution
Anti-patterns a eviter
Anti-patterns to avoid
Ne jamais modifier manuellement le ModelSnapshot Never manually modify the ModelSnapshot
Ne pas supprimer des migrations deja appliquees en production Don't delete migrations already applied in production
Eviter les migrations qui dependent de donnees specifiques Avoid migrations that depend on specific data
Ne pas utiliser SQL brut sans tester sur une copie Don't use raw SQL without testing on a copy

Integration avec GitFlow GitFlow Integration

SmartStack CLI integre la gestion des migrations EF Core directement dans le workflow GitFlow :

SmartStack CLI integrates EF Core migration management directly into the GitFlow workflow:

1
/gitflow init
Detection automatique
Automatic detection

Detecte EF Core et configure les DbContext dans le fichier de configuration.

Detects EF Core and configures DbContexts in the config file.

3
/gitflow commit
Validation des migrations
Migration validation

Valide que les 3 fichiers sont presents et detecte les operations destructives.

Validates that all 3 files are present and detects destructive operations.

4
/gitflow plan
Analyse des conflits
Conflict analysis

Detecte les conflits potentiels de ModelSnapshot entre branches.

Detects potential ModelSnapshot conflicts between branches.

5
/gitflow exec
Resolution automatique
Automatic resolution

Resout les conflits ModelSnapshot automatiquement pendant le rebase.

Resolves ModelSnapshot conflicts automatically during rebase.

Configuration

La configuration EF Core est stockee dans .claude/gitflow/config.json :

EF Core configuration is stored in .claude/gitflow/config.json:

{
  "efcore": {
    "enabled": true,
    "autoDetect": true,
    "contexts": [
      {
        "name": "CoreDbContext",
        "type": "core",
        "schema": "core",
        "projectPath": "./src/SmartStack.Domain",
        "migrationsFolder": "Persistence/Migrations",
        "startupProject": "./src/SmartStack.Api"
      },
      {
        "name": "ExtensionsDbContext",
        "type": "extensions",
        "schema": "extensions",
        "projectPath": "./src/Client.Domain",
        "migrationsFolder": "Persistence/Migrations",
        "startupProject": "./src/Client.Api"
      }
    ],
    "database": {
      "configFile": "appsettings.Local.json",
      "connectionStringName": "DefaultConnection",
      "provider": "SqlServer"
    },
    "naming": {
      "pattern": "{context}_v{version}_{sequence}_{Description}",
      "useMcp": true,
      "mcpTool": "mcp__smartstack__suggest_migration"
    },
    "crossBranch": {
      "enabled": true,
      "scanOnMigrationCreate": true,
      "blockOnConflict": true,
      "cacheExpiry": 300
    },
    "validation": {
      "validateBeforeCommit": true,
      "validateBeforeMerge": true,
      "checkModelSnapshotConflicts": true,
      "crossBranchValidation": true,
      "requireBuildSuccess": true,
      "warnOnPendingMigrations": true
    },
    "backup": {
      "enabled": true,
      "beforeRebase": true,
      "beforeSquash": true,
      "beforeMerge": true,
      "retentionDays": 7,
      "location": ".claude/gitflow/backup/migrations"
    },
    "rules": {
      "oneMigrationPerFeature": true,
      "recreateOnChange": true,
      "requireDescription": true,
      "validateNaming": true
    },
    "scripts": {
      "generateOnRelease": true,
      "outputPath": "./scripts/migrations",
      "idempotent": true
    }
  }
}