Database Migrations in C# (.NET) with Entity Framework
When developing applications in C# (.NET), one of the key tasks is synchronizing the data model (C# classes) with the database schema. Manually changing tables, columns, and relationships is a time-consuming and error-prone process. The solution to this problem is database migrations, a built-in mechanism of Entity Framework (EF) Core or Entity Framework 6. Migrations allow you to automatically apply changes to the database structure based on code changes while preserving existing data.
What are migrations and why are they needed?
A migration is a set of instructions (C# code) describing how to change the database schema from one version to another. Instead of writing SQL scripts manually, the developer modifies C# models (e.g., adds a new property to a class), and EF generates a migration file. This file is then applied to the database.
- Automation: Eliminates manual SQL writing.
- Versioning: Each migration is a separate file with a timestamp, allowing changes to be rolled back.
- Data safety: When adding a column, EF does not delete existing rows (unless specified otherwise).
- Collaboration: All team members apply the same migrations, preventing schema divergence.
Project Setup
To work with migrations, you need the installed package Microsoft.EntityFrameworkCore.Tools (for EF Core) or EntityFramework (for EF6). Installation via NuGet:
// For EF Core (via Package Manager Console)Install-Package Microsoft.EntityFrameworkCore.Tools
// Or via .NET CLIdotnet add package Microsoft.EntityFrameworkCore.ToolsYou will also need a database context inherited from DbContext. Example of a simple model:
public class Blog{ public int Id { get; set; } public string Title { get; set; } public string Content { get; set; }}
public class AppDbContext : DbContext{ public DbSet<Blog> Blogs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("Server=(localdb)\\\\mssqllocaldb;Database=MyBlogDb;Trusted_Connection=True;"); }}Creating the First Migration
Open the Package Manager Console (in Visual Studio: View -> Other Windows -> Package Manager Console) or use the .NET CLI. Run the command:
// Via PMCAdd-Migration InitialCreate
// Or via CLIdotnet ef migrations add InitialCreateAfter execution, a Migrations folder will appear in the project with two files:
XXXXXXXXXXXXXX_InitialCreate.cs— the migration class withUp()(what to change) andDown()(how to roll back) methods.AppDbContextModelSnapshot.cs— a snapshot of the current model.
Applying the Migration to the Database
To create or update the database to the latest version, run:
// Via PMCUpdate-Database
// Via CLIdotnet ef database updateEF will execute all unapplied migrations in order. If the database does not exist, it will be created automatically.
Adding a New Field and Creating a Migration
Suppose we decide to add a CreatedAt property to the Blog model:
public class Blog{ public int Id { get; set; } public string Title { get; set; } public string Content { get; set; } public DateTime CreatedAt { get; set; } // new field}Now create a new migration:
Add-Migration Also in library
Image Processing in C#: Resize and Crop
Sending SMS in Swift (iOS/macOS): MessageUI API and Third-Party Services
Monitoring PHP Applications with PHPMetrics
Generating PDF Reports in JavaScript (Node.js): Library Overview and Code Examples
Event Bus and Observer Pattern in C++: Implementation in Modern C++