Fix “Unable to Create a DbContext of Type” During EF Core Migrations
Quick answer. Point EF tools at both the migrations project and startup project. If the tools cannot construct the context from application services, provide an intentional design-time factory.
Applies to. EF Core with the provider and version used by your application.
What does the failure look like?
A context lives in a data library, while dependency registrations and configuration are in the web startup project.
How do you diagnose the cause?
Read the inner design-time error. Verify the SDK/tool and runtime packages are compatible, the projects build, the context constructor accepts DbContextOptions<T>, and the startup project supplies the provider and settings. Check environment-specific configuration.
Worked example
From the solution root, identify context, target project, and executable startup project. For a design-time factory, read configuration from an approved source and target the intended development database. Verify context discovery before running migration commands.
dotnet ef dbcontext info --project src/Data --startup-project src/Web --context AppDbContextIf the preview blocks the Copy button, select the snippet and copy it directly.
How do you verify the fix?
| Check | Expected behavior |
|---|---|
| Repeat the failing operation in development or staging | dbcontext info resolves AppDbContext and reports the intended provider. |
| Repeat normal traffic and a relevant negative case | Valid work completes and the failure path remains observable |
These are expected outcomes. The example was not executed against a deployed application.
Frequently asked question
Which project creates the context?
The startup project supplies services and configuration. The target project identifies where tooling creates its output.
Comments
Post a Comment