This post was most recently updated on September 19th, 2021.2 min read.
I’m using Entity Framework in most of the projects that I’m working on – and for the most part, it’s a pleasure to work with. But as always, there are plenty of chances to run into issues – so obviously, I stumble into all of the rare stuff that IS broken! This one I hadn’t really seen before – “No database provider has been configured for this DbContext”.
This time I encountered the issue while setting up a new project and getting started working on the model. EF Core simply fell on its back and started screaming like a 2-year old who didn’t get another juice box that they wanted.
Sometimes it just feels tough to get started, right? Well, let’s see what do we have today and how to resolve it!
So, another Entity Framework Core problem: While you’re running something like this (probably as your initial migration for a new database context) in your Visual Studio Package Manager Console:
You get an error like this:
No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
Okay – so how do we fix this?
Time needed: 5 minutes.
How to fix “No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider.” ?
- Make sure you’re running the Add-Migration commandlet against the right project
You can see the details on how to verify this from here:
- Override the OnConfiguring method
In your DbContext class, add something like this:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
This overridden method call will get called when your context gets instantiated (when running Add-Migration, anyone) – but you’ll then need to next configure the actual provider for this context.
- Add a call to your preferred database provider
This can be mocked – just have something like below in the OnConfiguring call:
Add-Migration won’t actually use this. And as long as the overridden method call isn’t called by you, this connection string won’t be used then, either. Or you could always add some logic around it to not actually use it.
Or maybe just don’t commit it in source control at all – it’s a dirty hack anyway :)
And we’re done!
- System.Text.Json.JsonPropertyName not working for CosmosDb in .NET Core/5? - October 19, 2021
- Errors loading an assembly that’s using Microsoft Graph API - October 12, 2021
- ILogger binding suddely failing for Azure Functions – what to do? - October 5, 2021