InvalidOperationException: No database provider has been configured for this DbContext.

Issue Description

EFCore runtime gives below error,

InvalidOperationException: 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.

No database provider has been configured for this DbContext

Resolution

The above error is most visible when DBContext instance is not configured properly either due to missing configuration at design time or runtime.

Please note that DBContext instance should have DbContextOptions which actually help setting up required DBContext details like which database provider to use and connection string etc.

I was able to fix the issue below two ways. Both ways producess the success results.

Resolution- I

Simple easy way to fix the issue is using DBContext with Dependency Injection. This Dependency injection is not possible if below 2 steps are not performed.

Step1 : Its recommended to to use AddDBContext method to inject the required DBContext injected in the Service IoC container as below,

No database provider has been configured for this DbContext

Step2: Using DBContext also require you to use Constructor Injections for DbContextOptions<TContext> object as below,

No database provider has been configured for this DbContext

Resolution II

If Overriding the OnConfiguring method then you can use DBContextOptionsbuilder to intialize the DbContextOption as below,

No database provider has been configured for this DbContext

If your code uses both above discussed option then use of the flag i.e optionBuilder.IsConfigured will decide which configuration to choose.

If you are using the latest EFCore tools for scaffolding DBContext or Migration, it does take care of adding the above configuration but if at if any issue exists in the above pattern please update the configuration manually.

References : Getting Started with EFCore with example

Did I miss anything else in these resolution steps?

Did the above steps resolve your issue? Please sound off your comments below!

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.