0Pricing
C# Academy · 课时

迁移与架构管理

创建、应用和回滚迁移,安全地演进数据库架构。

迁移与架构管理 是 CoddyKit 上的免费 C# Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 C# Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 C# Academy 课程共包含 4 节课。

什么是 EF Core 迁移

迁移是由代码生成的文件,用于描述数据库架构的增量更改。无需手动编写 DDL SQL,EF Core 会自动生成并应用这些更改,使代码与数据库保持同步。

安装 EF Core 工具

必须全局安装 EF Core CLI 工具(dotnet-ef),或将其安装为本地工具,才能从终端运行迁移命令。

# Install globally
dotnet tool install --global dotnet-ef

# Verify
dotnet ef --version

# Required NuGet packages in your project:
# Microsoft.EntityFrameworkCore.Design
# Microsoft.EntityFrameworkCore.SqlServer (or Sqlite, etc.)

创建您的第一个迁移

dotnet ef migrations add 会将当前模型与上一个快照进行比较,并生成一个迁移文件,其中包含用于应用更改的 Up() 方法和用于回滚的 Down() 方法。

# Create initial migration
dotnet ef migrations add InitialCreate

# Output files created:
# Migrations/20240101_InitialCreate.cs       <- Up/Down
# Migrations/20240101_InitialCreate.Designer.cs
# Migrations/AppDbContextModelSnapshot.cs   <- current model

迁移文件内部

每个迁移都有一个 Up 方法(应用更改)和一个 Down 方法(还原更改)。EF Core 会根据模型差异自动生成这些方法。

public partial class InitialCreate : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "Products",
            columns: table => new
            {
                Id    = table.Column<int>(nullable: false)
                             .Annotation("SqlServer:Identity", "1, 1"),
                Name  = table.Column<string>(maxLength: 200, nullable: false),
                Price = table.Column<decimal>(type: "decimal(18,2)", nullable: false)
            },
            constraints: table => table.PrimaryKey("PK_Products", x => x.Id));
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropTable(name: "Products");
    }
}

应用迁移

dotnet ef database update 会应用所有待处理的迁移。EF Core 会在 __EFMigrationsHistory 表中记录已经运行过的迁移。

# Apply all pending migrations
dotnet ef database update

# Apply up to a specific migration
dotnet ef database update AddProductIndex

# Roll back to a previous migration
dotnet ef database update InitialCreate

启动时以编程方式执行迁移

在生产环境中,您可以在应用启动时以编程方式应用迁移,使数据库始终保持最新状态,而无需手动执行 CLI 步骤。

var app = builder.Build();

// Apply pending migrations at startup
using (var scope = app.Services.CreateScope())
{
    var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
    await db.Database.MigrateAsync();
}

app.Run();

在新迁移中添加列

向实体添加一个属性,然后创建新的迁移。EF Core 会检测到此更改,并生成一个 AddColumn 操作。

// 1. Add property to entity
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public decimal Price { get; set; }
    public string? Description { get; set; } // NEW
}

// 2. Generate migration
// dotnet ef migrations add AddProductDescription

// Generated Up():
migrationBuilder.AddColumn<string>(
    name: "Description",
    table: "Products",
    nullable: true);

在迁移中植入数据

在 OnModelCreating 中使用 HasData 植入基础数据。EF Core 会将其作为 INSERT 语句包含在迁移的 Up 中。

modelBuilder.Entity<Category>().HasData(
    new Category { Id = 1, Name = "Electronics" },
    new Category { Id = 2, Name = "Books" },
    new Category { Id = 3, Name = "Clothing" }
);

// Then regenerate the migration:
// dotnet ef migrations add SeedCategories

迁移中的自定义 SQL

当您需要 EF Core 无法自动生成的 DDL(触发器、视图、存储过程)时,请使用 migrationBuilder.Sql()。

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.Sql(@"
        CREATE VIEW vw_ActiveProducts AS
        SELECT Id, Name, Price
        FROM Products
        WHERE IsActive = 1
    ");
}

protected override void Down(MigrationBuilder migrationBuilder)
{
    migrationBuilder.Sql("DROP VIEW vw_ActiveProducts");
}

移除迁移

如果某个迁移尚未应用,您可以使用 dotnet ef migrations remove 将其删除。使用此方式只能移除最后一个迁移。

# Remove the last unapplied migration
dotnet ef migrations remove

# List all migrations and their status
dotnet ef migrations list

# Script all migrations to SQL (for DBA review)
dotnet ef migrations script --output deploy.sql

实战:CI/CD 迁移策略

在 CI/CD 流水线中,生成迁移脚本,并在应用到生产环境之前交由 DBA 审查——切勿在关键生产系统中盲目运行 MigrateAsync()。

# Generate idempotent script for all pending migrations
dotnet ef migrations script --idempotent --output migrations.sql

# Review migrations.sql, then apply via sqlcmd / psql:
# sqlcmd -S server -d db -i migrations.sql

快速检查

EF Core 使用哪张表记录已经应用到数据库的迁移?

回顾:迁移与架构管理

核心要点:

  • dotnet ef migrations add <Name> 会生成增量架构更改文件
  • 每个迁移都有用于应用的 Up() 方法和用于回滚的 Down() 方法
  • dotnet ef database update 会应用待处理的迁移
  • 在应用启动时使用 MigrateAsync() 实现自动化部署
  • 在生产环境的流水线中生成幂等 SQL 脚本,供 DBA 审查

常见问题解答

「迁移与架构管理」课时是免费的吗?

是的 — 「迁移与架构管理」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 C# Academy 课程的其余内容,请升级到 CoddyKit PRO。 C# Academy 课程共包含 4 节课。

「迁移与架构管理」这节课中我会学到什么?

创建、应用和回滚迁移,安全地演进数据库架构。 你通过在浏览器中直接运行的动手代码来练习 C# Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 C# Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 C# Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「迁移与架构管理」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 C# Academy 课中编写并运行代码吗?

能。每节 C# Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. DbContext 与 DbSet 基础
  2. 迁移与架构管理
  3. 使用 EF Core 执行 CRUD 操作
  4. 关系:一对多与多对多
← 返回 C# Academy