skip to Main Content

I try to use DbContext from another class but I got exception down below.

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

I added ref project in my api app already.

Program.cs

using DAL.ModelContext;
using Microsoft.EntityFrameworkCore;

builder.Services.AddDbContext<MyDbContext>(options => 
    options.UseSqlServer(builder.Configuration.GetConnectionString("MyDbServer")));

MyDbContext.cs –> I deleted the code.

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{

}

Thx for your reply.

2

Answers


  1. There are two ways to configure the database Provider.

    One way is by adding the ‘AddDbContext’ in the application service (i.e) your program.cs file which you have done.

    builder.Services.AddDbContext(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("MyDbServer")));

    Here check whether you configured the connection string in the appsettings.json.

    "ConnectionStrings": { "MyDbServer": "Server=.;Database=<DbName>;Trusted_Connection=True;MultipleActiveResultSets=true" }
    

    Then Add the below constructor in your Context Class.

    public class MyDbContext : DbContext {
       public MyDbContext(DbContextOptions options) : base(options)
           {
           }
    }
    

    Other Method is by overriding the ‘DbContext.OnConfiguring’ method in your Context Class.

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer("Server=.\;Database=<DbName>;Trusted_Connection=True;");
            }
        }
    

    Check this out and let me know.

    Login or Signup to reply.
  2. I’ve been with this problem with a Test Project. I solved when I explicit declared in command line the LibraryProject and WebApi project, like that:

    dotnet ef migrations add InitDatabase --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose.
    

    And then, after, explicit as well with same "scaffold" to update database:

    dotnet ef database update --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose.
    

    I hope it could help someone.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search