What are Migrations?
Migrations allow you to evolve your database schema over time while preserving existing data. Essential for deploying database changes to Plesk hosting.
Setting Up Migrations
Install EF Core Tools:
dotnet tool install --global dotnet-ef
Creating Your First Migration
dotnet ef migrations add InitialCreate
This creates a Migrations folder with timestamped migration files.
Applying Migrations Locally
dotnet ef database update
Deployment Strategies for Plesk
Option 1: Apply Migrations on Startup (Recommended for Simple Apps)
// Program.cs
var app = builder.Build();
// Apply migrations on startup
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
db.Database.Migrate();
}
app.Run();
Warning: Not recommended for production apps with high availability requirements.
Option 2: Generate SQL Scripts (Recommended for Production)
dotnet ef migrations script -o migration.sql
- Generate the SQL script locally
- Review the script for safety
- Connect to your Plesk database via SQL Server Management Studio
- Execute the script manually
Option 3: Bundle Migrations (.NET 6+)
dotnet ef migrations bundle -o efbundle.exe
Deploy the bundle and run it against production database.
Creating Database in Plesk
- Log in to Plesk
- Go to Databases
- Click Add Database
- Select MS SQL Server
- Create database and user
- Update your production connection string
Common Migration Commands
# Create migration
dotnet ef migrations add AddProductTable
# Apply all migrations
dotnet ef database update
# Revert to specific migration
dotnet ef database update PreviousMigrationName
# Remove last migration (if not applied)
dotnet ef migrations remove
# Generate SQL script
dotnet ef migrations script
# Script from specific migration
dotnet ef migrations script FromMigration ToMigration
Handling Production Connection String
Use environment-specific appsettings:
// appsettings.Production.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=ProdDb;User Id=produser;Password=prodpass;TrustServerCertificate=True;"
}
}
For migrations against production (from local):
dotnet ef database update --connection "ProductionConnectionString"
Best Practices
- Always backup database before migrations
- Test migrations in staging environment first
- Review generated SQL before applying
- Keep migrations small and focused
- Never edit applied migrations