Entity Framework Core Interview Question #77

How does EF Core determine what to put in a new migration?

Migrations, Database Schema & Data Management Mid-Level Intermediate

Quick Interview Answer

When a new migration is created, EF Core compares the current model with the model snapshot associated with the previous migration. The differences are converted into migration operations.

Detailed Explanation

When a new migration is created, EF Core compares the current model with the model snapshot associated with the previous migration. The differences are converted into migration operations.

For example, adding a mapped property may produce an AddColumn operation, while adding a configured index may produce CreateIndex.

Because the migration is generated from model differences, developers should inspect both the migration code and the resulting SQL before deploying important schema changes.

Code Example

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.AddColumn<int>(
        name: "StockQuantity",
        table: "Products",
        nullable: false,
        defaultValue: 0);
}