Fix “No Database Provider Has Been Configured” for an EF Core DbContext
Quick answer. Ensure the exact context instance receives options with a provider configured. Register it with AddDbContext and resolve it through the correct request scope.
Applies to. EF Core with the provider and version used by your application.
What does the failure look like?
A repository manually calls new AppDbContext() even though the host registered it with SQL Server options.
How do you diagnose the cause?
Check the runtime constructor, verify it passes options to base, and find new calls or alternative registrations that bypass DI. If this only happens in dotnet ef, inspect the design-time factory separately. Install the provider package that matches the EF Core version.
Worked example
Configure the provider once in the host and require the typed options constructor. Read the connection string from the application configuration and fail clearly if missing. Keep scoped contexts out of singletons.
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("App")
?? throw new InvalidOperationException("Missing App connection string.")));
// In AppDbContext:
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }If 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 | The resolved context reports SQL Server and connects with the intended configuration. |
| 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
Why does DI work but new fails?
Manual construction bypasses registrations. Supply configured options explicitly or resolve through DI.
Comments
Post a Comment