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, likeAddCustomerTable.- 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.Toolspackage, 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
| Command | Description |
|---|---|
| dotnet ef migrations add MigrationName | Create a new migration with the given name |
| dotnet ef database update | Apply pending migrations to the database |
| dotnet ef migrations remove | Remove the last migration |
| dotnet ef migrations list | List 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.