dotnet data_error ai_generated true

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

其他格式: JSON · Markdown 中文 · English
92%修复率
90%置信度
1证据数
2023-05-20首次发现

版本兼容性

版本状态引入弃用备注
.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.

generic

官方文档

https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/applying

解决方案

  1. 从项目目录运行 'dotnet ef database update' 以应用所有待处理的迁移。
  2. 在 Program.cs 中,在构建服务提供程序后使用 context.Database.Migrate(),并在开发环境中用 try-catch 包裹。
  3. 如果使用 Docker,添加启动脚本,在应用程序启动前运行 'dotnet ef database update --connection <连接字符串>'。

无效尝试

常见但无效的做法:

  1. 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.

  2. 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.

  3. 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.