返回文章列表

已有数据库,如何应用EF Core迁移

2026-08-05

EF Core创建第一次迁移,会生成建表代码,但数据库中本来就有表,执行会报错:table already exists。

方法:创建第一次执行迁移:

1
dotnet-ef migrations add InitDb

此时会生成Migrations文件夹,其中有迁移脚本:时间戳_InitDb.cs,删除脚本中Up,Down方法中的内容:

1
2
3
4
5
6
7
8
9
protected override void Up(MigrationBuilder migrationBuilder)
{
    // 清空自动生成的建表代码,数据库本来就有表,不需要EF创建
}

protected override void Down(MigrationBuilder migrationBuilder)
{
    // Down也清空,回滚时不删表,防止删掉已有数据
}

应用迁移,让 EF 接管数据库:

1
dotnet-ef database update

迁移成功,数据库中会新增两张迁移记录表:__EFMigrationsHistory,__EFMigrationsLock。后续改动实体可正常新增迁移。

如果后续不想用迁移了:1.删除项目内 Migrations 文件夹;2.删除数据库中的__EFMigrationsHistory,__EFMigrationsLock表。

An unhandled error has occurred. Reload 🗙

Rejoining the server...

Rejoin failed... trying again in seconds.

Failed to rejoin.
Please retry or reload the page.

The session has been paused by the server.

Failed to resume the session.
Please retry or reload the page.