0
0
CsharpHow-ToBeginner · 3 min read

How to Create Migration in EF Core in C# - Step by Step Guide

To create a migration in EF Core using C#, use the dotnet ef migrations add MigrationName command in your project directory. This generates code to update your database schema based on your model changes.
📐

Syntax

The basic command to create a migration in EF Core is:

  • dotnet ef migrations add MigrationName: Creates a new migration with the specified name.
  • MigrationName: A descriptive name for the migration, like AddCustomerTable.
  • This command must be run in the project folder containing your EF Core DbContext.
bash
dotnet ef migrations add MigrationName
💻

Example

This example shows how to create a migration after adding a new property to a model class.

First, update your model class:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }  // New property added
}

Then run the migration command in your project folder:

bash
dotnet ef migrations add AddPriceToProduct
Output
Build succeeded. To undo this action, use 'dotnet ef migrations remove'. Migration 'AddPriceToProduct' was added successfully.
⚠️

Common Pitfalls

Common mistakes when creating migrations include:

  • Running the command outside the project folder with the DbContext causes errors.
  • Not installing the Microsoft.EntityFrameworkCore.Tools package, which is required for migrations.
  • Forgetting to update the model before creating a migration results in empty migrations.
  • Not applying the migration to the database using dotnet ef database update.
bash
/* Wrong: Running migration command outside project folder */
// Error: No DbContext was found

/* Right: Navigate to project folder first */
// cd YourProjectFolder
// dotnet ef migrations add MigrationName
📊

Quick Reference

CommandDescription
dotnet ef migrations add MigrationNameCreate a new migration with the given name
dotnet ef database updateApply pending migrations to the database
dotnet ef migrations removeRemove the last migration
dotnet ef migrations listList all migrations in the project

Key Takeaways

Run 'dotnet ef migrations add MigrationName' in the project folder with your DbContext.
Always update your model classes before creating a migration to capture changes.
Install 'Microsoft.EntityFrameworkCore.Tools' package to enable migration commands.
Apply migrations to the database using 'dotnet ef database update' after creating them.
Avoid running migration commands outside the project directory to prevent errors.