# System.InvalidOperationException: 访问数据库时出错。继续运行但没有应用程序的数据库上下文。数据库可能有待处理的迁移。请应用迁移后重试。

- **ID:** `dotnet/ef-core-migration-pending`
- **领域:** dotnet
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 92%

## 根因

ASP.NET Core 应用程序因数据库架构与 EF Core 模型不匹配（存在待处理的迁移或数据库缺失）而无法启动。

## 版本兼容性

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

## 解决方案

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

## 无效尝试

- **Delete the database and let EF Core recreate it automatically** — Deleting the database loses all data; in production this causes data loss and downtime. The error is about pending migrations, not missing database. (95% 失败率)
- **Set EnsureCreated() instead of Migrate() in Program.cs** — 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. (80% 失败率)
- **Remove all migration files and add a new initial migration** — Removing migrations loses the migration history; the new initial migration may conflict with existing database state. (75% 失败率)
