dotnet data_error ai_generated true

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

Also available as: JSON · Markdown · 中文
92%Fix Rate
90%Confidence
1Evidence
2023-05-20First Seen

Version Compatibility

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

Root Cause

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

中文

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

Official Documentation

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

Workarounds

  1. 90% success Run 'dotnet ef database update' from the project directory to apply all pending migrations.
    Run 'dotnet ef database update' from the project directory to apply all pending migrations.
  2. 85% success In Program.cs, use context.Database.Migrate() after building the service provider, wrapped in try-catch for development environments.
    In Program.cs, use context.Database.Migrate() after building the service provider, wrapped in try-catch for development environments.
  3. 88% success If using Docker, add a startup script that runs 'dotnet ef database update --connection <connection_string>' before the application starts.
    If using Docker, add a startup script that runs 'dotnet ef database update --connection <connection_string>' before the application starts.

中文步骤

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

Dead Ends

Common approaches that don't work:

  1. Delete the database and let EF Core recreate it automatically 95% fail

    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% fail

    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% fail

    Removing migrations loses the migration history; the new initial migration may conflict with existing database state.