System.InvalidOperationException: 访问数据库时出错。继续运行但没有应用程序的数据库上下文。数据库可能有待处理的迁移。请应用迁移后重试。
System.InvalidOperationException: An error occurred while accessing the database. Continuing without the application's database context. The database may have pending migrations. Apply migrations and try again.
ID: dotnet/ef-core-migration-pending
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| .NET 6.0 | active | — | — | — |
| .NET 7.0 | active | — | — | — |
| .NET 8.0 | active | — | — | — |
| EF Core 6.0 | active | — | — | — |
| EF Core 7.0 | active | — | — | — |
| EF Core 8.0 | active | — | — | — |
根因分析
ASP.NET Core 应用程序因数据库架构与 EF Core 模型不匹配(存在待处理的迁移或数据库缺失)而无法启动。
English
ASP.NET Core application fails to start because the database schema does not match the EF Core model due to pending migrations or missing database.
官方文档
https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/applying解决方案
-
从项目目录运行 'dotnet ef database update' 以应用所有待处理的迁移。
-
在 Program.cs 中,在构建服务提供程序后使用 context.Database.Migrate(),并在开发环境中用 try-catch 包裹。
-
如果使用 Docker,添加启动脚本,在应用程序启动前运行 'dotnet ef database update --connection <连接字符串>'。
无效尝试
常见但无效的做法:
-
Delete the database and let EF Core recreate it automatically
95% 失败
Deleting the database loses all data; in production this causes data loss and downtime. The error is about pending migrations, not missing database.
-
Set EnsureCreated() instead of Migrate() in Program.cs
80% 失败
EnsureCreated() skips migrations and creates a schema based on the current model, but it will fail if the database already exists with a different schema.
-
Remove all migration files and add a new initial migration
75% 失败
Removing migrations loses the migration history; the new initial migration may conflict with existing database state.