Entity Framework Migrations
Entity Framework (EF) Migrations provides a way to incrementally update your SQL Server database schema to match your entity model without having to manually write database upgrade scripts.
EF Migrations allows you to evolve your database schema over time as your application's domain model changes. It handles schema updates by generating and applying SQL scripts.
Key Concepts and Workflow
- Enable Migrations: You first enable Migrations for your EF DbContext. This creates a
Migrations
folder in your project containing the configuration for Migrations. - Add Migration: When you make changes to your entity classes or
DbContext
, you create a new migration. EF compares your current model with the last migration and generates code to represent the schema changes. - Update Database: You then apply the generated migration to your database. EF executes the generated SQL scripts to update the database schema.
- Generate Script: Alternatively, you can generate a SQL script from a migration to review or apply manually.
Common Commands
Migrations are typically managed using the Package Manager Console in Visual Studio or via the .NET CLI.
Package Manager Console (Visual Studio)
Ensure you have the Microsoft.EntityFrameworkCore.Tools
or EntityFramework.Commands
(for older EF versions) NuGet package installed.
# Enable migrations for the first time
Enable-Migrations
# Add a new migration with a descriptive name
Add-Migration InitialCreate
# Apply the latest migration to the database
Update-Database
# Generate a SQL script for a migration
Update-Database -Script -SourceMigration :0 -TargetMigration :Latest
# Drop and recreate the database (use with caution!)
Drop-Database
.NET CLI
Ensure you have the Microsoft.EntityFrameworkCore.Design
NuGet package installed.
# Navigate to your project directory in the terminal
# Enable migrations (creates Migrations folder and Configuration.cs)
dotnet ef migrations add InitialCreate
# Add a new migration
dotnet ef migrations add AddNewPropertyToUser
# Apply the latest migration to the database
dotnet ef database update
# Generate a SQL script
dotnet ef migrations script 0
Scaffolding Migrations
When you add a migration, EF generates two files in the Migrations
folder:
- A
.Designer.cs
file: Contains the automatically generated code for the migration, includingUp()
andDown()
methods. - A
.cs
file: Contains the migration configuration, which you can customize.
Example: Adding a new property
Suppose you have an User
entity:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
And you add a new property Email
:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; } // New property
}
Running Add-Migration AddEmailToUser
would generate code similar to:
// Auto-generated Migration
public partial class AddEmailToUser : DbMigration
{
public override void Up()
{
AddColumn("dbo.Users", "Email", c => c.String());
}
public override void Down()
{
DropColumn("dbo.Users", "Email");
}
}
Best Practices and Considerations
- Descriptive Names: Always use descriptive names for your migrations (e.g.,
AddUserTable
,RenameColumnToNewName
). - Review Generated Code: Thoroughly review the code generated by EF Migrations, especially for complex changes.
- Manual Edits: You can manually edit the generated migration code to fine-tune the SQL.
- Empty Migrations: For custom SQL scripts that don't map directly to model changes, use
Add-Migration Init
and then edit the generated migration'sUp()
andDown()
methods to include your custom SQL. - Seed Data: Use the
Seed()
method in your migration configuration class to populate initial data or reference data into your database. - Version Control: Commit your migration files to your version control system alongside your application code.
Note on Version Compatibility
Ensure that the version of the EF Tools NuGet package you are using is compatible with your EF version and .NET SDK. Older versions of EF (like EF6) have different tooling commands than EF Core.
Important: Production Deployments
When deploying to production, it's generally recommended to generate SQL scripts and have a database administrator apply them, rather than directly running Update-Database
. This allows for better control and auditing.