Entity Framework Core Migrations for Plesk Deployment Print

  • 0

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
  1. Generate the SQL script locally
  2. Review the script for safety
  3. Connect to your Plesk database via SQL Server Management Studio
  4. 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

  1. Log in to Plesk
  2. Go to Databases
  3. Click Add Database
  4. Select MS SQL Server
  5. Create database and user
  6. 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

Was this answer helpful?

« Back