Entity Framework Core Migrations: Managing Schema Changes

On this page

EF Core migrations track database schema changes alongside your code. Here’s how to use them effectively.

Basic Commands

Bash11 lines
# Create migration
dotnet ef migrations add AddUserTable

# Apply migrations
dotnet ef database update

# Revert to specific migration
dotnet ef database update PreviousMigrationName

# Generate SQL script
dotnet ef migrations script

Migration File

C#20 lines
public partial class AddUserTable : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "Users",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false)
                    .Annotation("SqlServer:Identity", "1, 1"),
                Email = table.Column<string>(maxLength: 256)
            },
            constraints: table => table.PrimaryKey("PK_Users", x => x.Id));
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropTable("Users");
    }
}

Best Practices

  • Always review generated migrations
  • Test Down() methods
  • Use SQL scripts for production
  • Consider data migrations separately

References


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Written by

Nithin Mohan TK

Hello Namaste! 👋🏻 I'm an accomplished Enterprise Solution Architect & Engineering Leader with 20+ years of progressive experience architecting, building, and scaling transformative enterprise solutions. ⚜️ Solution Architect / AI & Cloud 📌 Galway, Ireland

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.