No database provider has been configured for this DbContext, even when passing DbContextOptions to constructor

44 Views Asked by At

I have seen many issues online for this, however the answer seems to be to make sure your DbContext class has a constructor for DbContextOptions.

However, i have debugged, and I can see that the correct constructor is being called, Yet I am still getting the "No database provider has been configured for this DbContext" error : (

Here is the relevant code from my Controller.cs:

Microsoft.EntityFrameworkCore.DbContextOptions<CoreContext> options = new Microsoft.EntityFrameworkCore.DbContextOptions<CoreContext>();
using (CoreContext dbContext = new CoreContext(options)) 
{
    dbContext.Person.Add(person);
    dbContext.SaveChanges();
    id = person.PkPersonId;
}

This is the constructor for my CoreContext.cs:

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

And here is my Startup.cs Configuration method:

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            services.AddIdentity<IdentityUser, IdentityRole>(options => { options.Password.RequiredLength = 10; })
                .AddEntityFrameworkStores<CoreContext>();

            services.AddDbContext<CoreContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")));

        }
2

There are 2 best solutions below

2
Nilamani On

You need to define the entities details under DBContext then only you can able to access the database entities otherwise you will get the error. So please follow below code for resolving this issue.

public CoreContext(DbContextOptions<CoreContext> options): base(options)
{
   public virtual DbSet<Person> Persons { get; set; }
}
0
treendy On

I needed to use the container version instead of trying to instantiate the DbContext again

So, just injected the Dbcontext into my controller:

        private CoreContext _coreContext;

        public AccountController(CoreContext coreContext)
        {
             private CoreContext _coreContext;

then changed the following code from:

Microsoft.EntityFrameworkCore.DbContextOptions<CoreContext> options = new Microsoft.EntityFrameworkCore.DbContextOptions<CoreContext>();
using (CoreContext dbContext = new CoreContext(options)) 
{
    dbContext.Person.Add(person);
    dbContext.SaveChanges();
    id = person.PkPersonId;
}

To just:

_coreContext.Person.Add(person);
_coreContext.SaveChanges();
id = person.PkPersonId;