Entity Framework (EF) Migrations is a powerful feature that allows you to evolve your database schema over time as your application's model changes.
Migrations are a series of C# classes that represent changes to your database schema. When you make changes to your EF Core model (like adding a new entity, property, or relationship), EF Core can generate a migration that describes how to update your database to match that new model. This ensures your database schema stays synchronized with your application code.
Up() method) and to revert them (Down() method).DbContext: Your main class for interacting with the database. Migrations are tied to your DbContext.Add-Migration (Package Manager Console): Command to scaffold a new migration based on changes in your model.dotnet ef migrations add (CLI): Equivalent command for .NET CLI users.Update-Database (Package Manager Console): Command to apply pending migrations to your database.dotnet ef database update (CLI): Equivalent command for .NET CLI users.Here's the typical process for using EF Core Migrations:
DbContext configuration. For example, add a new property to an existing entity:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Description { get; set; } // New property
}
Ensure you have the Microsoft.EntityFrameworkCore.Tools NuGet package installed.
Add-Migration AddProductDescription
Ensure you have the Microsoft.EntityFrameworkCore.Design NuGet package installed.
dotnet ef migrations add AddProductDescription
This command generates two files in your Migrations folder:
YYYYMMDDHHMMSS_AddProductDescription.cs) containing the Up() and Down() methods.YourDbContextModelSnapshot.cs) representing the current state of your model.Up() method. EF Core is usually good at generating schema changes, but you might need to manually adjust it, especially for complex scenarios.
public partial class AddProductDescription : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Description",
table: "Products",
type: "nvarchar(max)",
nullable: true); // Note: nullable might depend on your configuration
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Description",
table: "Products");
}
}
Update-Database
dotnet ef database update
This command will execute the Up() method of all pending migrations.
DbContext.migrationBuilder.Sql() within your migration's Up() and Down() methods.Up() method of an early migration.Update-Database -TargetMigration InitialCreate (to go back to a specific migration) or delete migration files and then re-run Update-Database (use with extreme caution!).