Entity Framework Core Migrations: Complete Beginner Guide for ASP.NET Core
Database structures evolve over time. New tables are added, columns are modified, relationships change, and indexes need optimization. Managing these changes manually can become difficult and error-prone.
Entity Framework Core Migrations provide a reliable way to track and apply database schema changes directly from your C# code. Instead of manually writing SQL scripts for every update, migrations automate the process.
In this tutorial, you'll learn how migrations work, how to create them, apply them, and manage database changes in professional ASP.NET Core applications.
- What Are EF Core Migrations?
- Installing Migration Tools
- Creating Models
- Creating Migrations
- Updating Databases
- Removing Migrations
- Generating SQL Scripts
- Common Problems
- Best Practices
What Are Entity Framework Core Migrations?
Migrations are a feature of Entity Framework Core that allow developers to keep a database schema synchronized with application models.
When your model classes change, EF Core can generate migration files that describe the necessary database changes.
Examples include:
- Creating new tables.
- Adding columns.
- Renaming columns.
- Deleting tables.
- Creating indexes.
- Adding relationships.
Why Use Migrations?
Without migrations, database changes often require manually writing SQL scripts and keeping track of modifications.
Migrations provide:
- Version control for database schemas.
- Repeatable deployment processes.
- Automatic schema updates.
- Team collaboration support.
- Reduced human error.
Create a Sample Project
dotnet new mvc -n MigrationDemo
cd MigrationDemo
Install Required Packages
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
These packages provide Entity Framework Core functionality, SQL Server support, and migration commands.
Create a Model
Create a Product model that represents a database table.
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = "";
public decimal Price { get; set; }
}
Create the DbContext
using Microsoft.EntityFrameworkCore;
public class ApplicationDbContext
: DbContext
{
public ApplicationDbContext(
DbContextOptions<ApplicationDbContext>
options)
: base(options)
{
}
public DbSet<Product> Products
{
get; set;
}
}
Configure the Connection String
{
"ConnectionStrings": {
"DefaultConnection":
"Server=(localdb)\\MSSQLLocalDB;
Database=MigrationDemo;
Trusted_Connection=True;"
}
}
Register DbContext
builder.Services.AddDbContext
<ApplicationDbContext>(options =>
{
options.UseSqlServer(
builder.Configuration
.GetConnectionString(
"DefaultConnection"));
});
Create Your First Migration
Open a terminal and run:
dotnet ef migrations add InitialCreate
EF Core will analyze your model classes and generate migration files.
Generated Migration Example
public partial class InitialCreate
: Migration
{
protected override void Up(
MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Products",
columns: table => new
{
Id = table.Column<int>(),
Name = table.Column<string>(),
Price = table.Column<decimal>()
});
}
protected override void Down(
MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
"Products");
}
}
Apply the Migration
Run the following command:
dotnet ef database update
EF Core creates the database and applies the migration.
Verify the Database
After running the update command, you should see:
- Products table.
- __EFMigrationsHistory table.
The history table tracks which migrations have been applied.
Adding a New Column
Suppose we want to add a Stock property.
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = "";
public decimal Price { get; set; }
public int Stock { get; set; }
}
Generate a new migration:
dotnet ef migrations add AddStockColumn
Apply the update:
dotnet ef database update
EF Core automatically adds the new column.
View Existing Migrations
dotnet ef migrations list
Example output:
InitialCreate
AddStockColumn
Remove the Last Migration
If a migration hasn't been applied yet:
dotnet ef migrations remove
This removes the most recently created migration.
Rollback a Database
Revert to a previous migration:
dotnet ef database update InitialCreate
EF Core executes the Down methods to reverse changes.
Generate SQL Scripts
Many production environments require SQL scripts instead of direct updates.
dotnet ef migrations script
Generate a specific migration range:
dotnet ef migrations script
InitialCreate
AddStockColumn
This produces SQL that can be reviewed before deployment.
Understanding Up and Down Methods
| Method | Purpose |
|---|---|
| Up() | Apply schema changes. |
| Down() | Reverse schema changes. |
Common Migration Problems
Missing Tools
dotnet tool install --global dotnet-ef
Connection String Errors
Verify your database server name and credentials.
Model Not Updating
Ensure you've created a new migration after modifying models.
Migration Workflow Example
- Create or modify model classes.
- Create a migration.
- Review generated code.
- Apply migration to development database.
- Test changes.
- Deploy migration to production.
Best Practices
- Create small, focused migrations.
- Review migration code before applying.
- Use source control for migrations.
- Back up production databases.
- Generate SQL scripts for production deployments.
- Avoid manually editing migration history tables.
Frequently Asked Questions
Do migrations create databases?
Yes. The database update command can create a database if it does not already exist.
Can migrations update existing databases?
Yes. Migrations can add, remove, or modify schema objects.
Should migration files be committed to Git?
Yes. Migration files should be included in source control so team members can apply the same database changes.
Can I roll back migrations?
Yes. EF Core allows reverting to previous migration states.
Related Tutorials
- Entity Framework Core CRUD
- Repository Pattern in ASP.NET Core
- Dependency Injection in ASP.NET Core
- LINQ Cheat Sheet
- ASP.NET Core MVC Tutorial
Conclusion
Entity Framework Core Migrations provide a safe and structured way to manage database schema changes throughout the development lifecycle.
By understanding how to create, apply, rollback, and deploy migrations, you'll be better equipped to build maintainable ASP.NET Core applications that evolve over time without losing database consistency.