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
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.
Here check whether you configured the connection string in the appsettings.json.
Then Add the below constructor in your Context Class.
Other Method is by overriding the ‘DbContext.OnConfiguring’ method in your Context Class.
Check this out and let me know.
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:
And then, after, explicit as well with same "scaffold" to update database:
I hope it could help someone.