EF Core Add Migration — Complete Guide
In this tutorial, you'll learn about EF Core Add Migration. We cover key concepts, practical examples, and best practices.
You change a model class — adding a property, renaming a column, or creating a new entity. The database is out of sync. You manually run ALTER TABLE statements that drift from your code. EF Core migrations generate and apply schema changes automatically from your model changes.
Wrong
// Add a new property to the model but never update the database
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Category { get; set; } // New — DB doesn't have this column
}
Output: InvalidOperationException or SqlException when querying — column Category does not exist.
Right
# Terminal
dotnet ef migrations add AddCategoryToProduct
This generates:
public partial class AddCategoryToProduct : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Category",
table: "Products",
type: "nvarchar(max)",
nullable: false,
defaultValue: "");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Category",
table: "Products");
}
}
Apply:
dotnet ef database update
// Or in code:
await db.Database.MigrateAsync();
Prevention
- Run
dotnet ef migrations add <Name>after every model change. - Review the generated migration before applying it.
- Use
dotnet ef migrations listto see pending migrations. - Use
dotnet ef database updateto apply to local/dev databases. - Use
db.Database.MigrateAsync()in production startup (with caution). - Check the migration
Down()method — it must reverseUp()exactly. - Use
migrationBuilder.Sql()for custom SQL that migrations cannot express.
Common Mistakes with core migration add
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
These mistakes appear frequently in real-world EF code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Learn more about EF Core migrations at DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro