# Install EF Core tools (one-time setup)
dotnet tool install --global dotnet-ef
# Update EF Core tools
dotnet tool update --global dotnet-ef
# Verify installation
dotnet ef --version# Navigate to project directory
cd SecureBootDashboard.Api
# Create migration
dotnet ef migrations add MigrationName
# Create migration with startup project (if different)
dotnet ef migrations add MigrationName --startup-project ../SecureBootDashboard.WebNaming conventions:
AddColumnNameToTable- e.g.,AddClientVersionToDeviceCreateTableName- e.g.,CreateAuditLogUpdateTableNameStructure- e.g.,UpdateDeviceStructure
# Remove last migration (only if not applied to database)
dotnet ef migrations remove
# Force remove (use with caution)
dotnet ef migrations remove --force?? Warning: Only remove migrations that haven't been applied to the database!
# Apply to database specified in appsettings.json
dotnet ef database update
# Apply with custom connection string
dotnet ef database update --connection "Server=...;Database=...;Trusted_Connection=True"# Apply up to specific migration
dotnet ef database update MigrationName
# Rollback to specific migration
dotnet ef database update PreviousMigrationName# Remove all migrations from database (keeps data)
dotnet ef database update 0?? Warning: This will drop all tables!
dotnet ef migrations listOutput:
20251105093532_InitialCreate (Applied)
20251105101836_AddCertificateCollection (Applied)
20251109202217_AddClientVersionToDevice (Pending)
# Generate SQL for next migration
dotnet ef migrations script
# Generate SQL for specific migration
dotnet ef migrations script PreviousMigration TargetMigration
# Generate SQL for all pending migrations
dotnet ef migrations script --idempotent
# Output to file
dotnet ef migrations script --output migration.sql# Generate SQL to create database from scratch
dotnet ef dbcontext script
# Output to file
dotnet ef dbcontext script --output schema.sql# Drop database (all data lost!)
dotnet ef database drop
# Drop without confirmation
dotnet ef database drop --force# Drop and recreate
dotnet ef database drop --force
dotnet ef database update# List all DbContexts in project
dotnet ef dbcontext list
# View DbContext info
dotnet ef dbcontext info# Create self-contained migration executable
dotnet ef migrations bundle
# Specify output
dotnet ef migrations bundle --output migrations.exe
# Run bundle
.\migrations.exe --connection "Server=...;Database=...;Trusted_Connection=True"# Clean build
dotnet clean
dotnet build
# Verbose output
dotnet ef database update --verbose{
"ConnectionStrings": {
"SqlServer": "Server=SRVSQL;Database=SecureBootDashboard;Trusted_Connection=True;TrustServerCertificate=True"
}
}{
"ConnectionStrings": {
"SqlServer": "Server=localhost;Database=SecureBootDashboard_Dev;Trusted_Connection=True;TrustServerCertificate=True"
}
}public partial class AddClientVersionToDevice : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "ClientVersion",
table: "Devices",
type: "nvarchar(50)",
maxLength: 50,
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "ClientVersion",
table: "Devices");
}
}# 1. Update entity model (DeviceEntity.cs)
# 2. Create migration
dotnet ef migrations add AddNewColumnToDevice
# 3. Review generated migration
code Data/Migrations/*_AddNewColumnToDevice.cs
# 4. Apply migration
dotnet ef database update# 1. Update entity model
# 2. Create migration
dotnet ef migrations add RenameOldColumnToNewColumn
# 3. Edit migration to use RenameColumn (not Add/Drop)
# 4. Apply migration
dotnet ef database updateManual edit example:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "OldName",
table: "Devices",
newName: "NewName");
}# 1. Update entity model
# 2. Create migration
dotnet ef migrations add ChangeColumnTypeForDevice
# 3. Apply migration (may require data migration)
dotnet ef database update# Option 1: Remove last migration (if not applied)
dotnet ef migrations remove
# Option 2: Rollback to previous migration
dotnet ef database update PreviousMigrationName
# Option 3: Create new migration to fix
dotnet ef migrations add FixBrokenMigration- Always review generated migrations before applying
- Test migrations on development database first
- Use meaningful migration names
- Commit migrations to source control
- Generate SQL scripts for production deployments
- Back up database before major migrations
- Use idempotent scripts for production
- Don't remove applied migrations from source control
- Don't modify applied migrations (create new one instead)
- Don't skip testing migrations
- Don't apply migrations directly to production (use scripts)
- Don't forget to update model snapshot
- Don't use
database dropin production
# Development environment
dotnet ef migrations script --idempotent --output migration.sql# Review SQL before applying
code migration.sql-- SQL Server Management Studio
BACKUP DATABASE SecureBootDashboard
TO DISK = 'C:\Backups\SecureBootDashboard_PreMigration.bak'
WITH INIT, COMPRESSION;-- Execute migration.sql in SSMS
-- Or use sqlcmd:
sqlcmd -S SRVSQL -d SecureBootDashboard -i migration.sql-- Check applied migrations
SELECT * FROM __EFMigrationsHistory
ORDER BY MigrationId DESC;# Use Development connection string
$env:ASPNETCORE_ENVIRONMENT = "Development"
dotnet ef database update# Use Production connection string
$env:ASPNETCORE_ENVIRONMENT = "Production"
dotnet ef migrations script --idempotent --output production_migration.sql# Use provided script
.\scripts\Apply-DatabaseMigrations.ps1 -Force# Check if migrations needed
$pendingMigrations = dotnet ef migrations list 2>&1 | Select-String "Pending"
if ($pendingMigrations) {
Write-Host "Pending migrations found. Applying..."
dotnet ef database update
} else {
Write-Host "Database is up to date."
}| Error | Solution |
|---|---|
dotnet ef: command not found |
dotnet tool install --global dotnet-ef |
Build failed |
dotnet clean && dotnet build |
Unable to create migration |
Check entity model changes |
Login failed |
Verify connection string |
Network-related error |
Check SQL Server service is running |
Duplicate migration |
Remove duplicate with migrations remove |
Column already exists |
Check if migration already applied |
Foreign key constraint |
Review migration order |
dotnet ef migrations list | Select-String "Pending"-- Direct database query
SELECT * FROM __EFMigrationsHistory
ORDER BY MigrationId DESC;# Generate current model script
dotnet ef dbcontext script --output current_model.sql
# Compare with database
# Use SQL Server Schema Compare tool- Official Documentation: https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/
- Migration Tutorial: https://learn.microsoft.com/en-us/ef/core/get-started/overview/first-app
- Database Providers: https://learn.microsoft.com/en-us/ef/core/providers/
Quick Command Reference Card
# Create migration
dotnet ef migrations add MigrationName
# Apply migrations
dotnet ef database update
# List migrations
dotnet ef migrations list
# Generate SQL
dotnet ef migrations script --idempotent
# Remove last migration (if not applied)
dotnet ef migrations remove
# Drop database
dotnet ef database drop --forceLast Updated: 2025-01-10