devonuto
devonuto

Reputation: 423

AddDbContext not working in net Core 5.0 web api

I have this in my Startup:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<MyDbContext>(options => 
        options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"))
    );
    . . .
}

and I have this in my database context:

 public MyDbContext(DbContextOptions<MyDbContext> options)
     : base(options)
 {            
 }

But when I go to access the DB, I get this:

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

I shouldn't need to use both the overriding DbContext.OnConfiguring method. Why is this not working?

Configuration.GetConnectionString("DefaultConnection")

is returning the correct value, so I'm stumped.

EDIT: I should note, this occurs when calling a "SetGlobals" method, which populates some variables used throughout the api, and not called directly from a Controller.

Upvotes: 1

Views: 725

Answers (1)

devonuto
devonuto

Reputation: 423

Not really an explanation of why it doesn't work, but changing

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<MyDbContext>(options => 
        options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"))
    );
    . . .
}

to

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<MyDbContext>();
    . . .
}

in Startup and adding the following to MyDBContext gets it working.

 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
 {
     if (!optionsBuilder.IsConfigured)
     {
         IConfigurationRoot configuration = new ConfigurationBuilder()
             .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
             .AddJsonFile("appsettings.json")
             .Build();

         optionsBuilder.UseSqlite(configuration.GetConnectionString("DefaultConnection"));
     }
 }

Upvotes: 1

Related Questions