Entity Framework Migrations
Entity Framework Migrations is a powerful feature that enables you to evolve your data model over time while keeping your database schema in sync. It allows you to manage changes to your code-first or model-first entities and automatically generate the corresponding database schema changes.
What are Migrations?
Migrations are essentially a series of incremental, versioned changes to your database schema. Each migration represents a specific set of changes, such as adding a new table, modifying a column, or dropping an index. Entity Framework tracks these migrations, allowing you to apply them forward to update your database or revert them to a previous state.
Key Concepts
- Code-First Migrations: The most common scenario where your database schema is generated from your C# or VB.NET model classes.
- Model Changes: Any modification to your entity classes (e.g., adding properties, changing data types, defining relationships) is considered a model change.
- Migration Scripts: When you enable migrations and make model changes, Entity Framework can generate C# scripts that represent these changes.
- Applying Migrations: You can apply pending migrations to update your database schema to match the current model.
- Reverting Migrations: You can roll back to a previous migration if needed.
Getting Started with Migrations
1. Enabling Migrations
To start using migrations, you first need to enable them in your project. Open the Package Manager Console (Tools > NuGet Package Manager > Package Manager Console) and run the following command:
Enable-Migrations
This command will create a Migrations
folder in your project, containing an initial migration file and a Configuration.cs
file. The Configuration.cs
file allows you to configure how migrations are applied.
2. Making Model Changes and Creating a New Migration
After enabling migrations, make changes to your entity classes. For example, add a new property to an existing entity:
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Description { get; set; } // New property
}
Once you've made your changes, generate a new migration by running:
Add-Migration AddDescriptionToProduct
Replace AddDescriptionToProduct
with a descriptive name for your migration. This command creates a new C# file in the Migrations
folder, detailing the changes needed to update your database schema.
3. Applying Migrations to the Database
To apply the pending migration(s) and update your database schema, use the following command:
Update-Database
If you want to apply a specific migration, you can provide its name or its ID:
Update-Database -TargetMigration AddDescriptionToProduct
Common Migration Operations
- Viewing Pending Migrations:
Get-Migrations
- Reverting to a Previous Migration:
Update-Database -TargetMigration PreviousMigrationName
- Reverting All Migrations:
Update-Database -TargetMigration 0
- Scaffolding a Migration from Existing Database:
Scaffold-DbContext
(This is for reverse engineering an existing database into an EF Core model.)
Configuration Options
The Configuration.cs
file in the Migrations
folder provides several options:
- AutomaticMigrationsEnabled: Set to
true
if you want EF to automatically create migrations for model changes (use with caution, especially in production). - AutomaticMigrationDataLossAllowed: Set to
true
to allow automatic migrations that might result in data loss (e.g., dropping a column). Use with extreme caution! - Seed Method: The
Seed()
method allows you to populate your database with initial data after a migration is applied.
internal sealed class Configuration : DbMigrationsConfiguration<YourDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false; // Set to true for automatic migrations
AutomaticMigrationDataLossAllowed = false; // Set to true with extreme caution
}
protected override void Seed(YourDbContext context)
{
// Seed your database here
// context.Products.AddOrUpdate(p => p.Name, new Product { Name = "Sample Product", Price = 19.99M });
}
}
Sql()
method within a migration to execute custom SQL statements.
Best Practices
- Use descriptive names for your migrations.
- Review migration scripts thoroughly.
- Avoid automatic migrations in production environments unless you have a robust testing strategy.
- Commit your migration files to source control along with your code.