I have ASP.NET Core MVC project with .NET 7.
I want put my SQL Server connection string in appsetting file. Then use that in my entire project and the layers.
But I get the provider error:
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<TContext> object in its constructor and passes it to the base constructor for DbContext.'
How can fix this?
What I have tried:
This is my appsetting:
"ConnectionStrings": {
"CON1": "data source=DESKTOP-JU6B74d\\SQL2019;initial catalog = Laser; integrated security = true;TrustServerCertificate=True;"
},
This is the program file setting for
dbcontext
:
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<DB>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("Con1")));
And this is part of my
dbcontext
in data access layer:
public class DB: IdentityDbContext
{
public DB() : base() { }
public DB(DbContextOptions<DB> options) : base(options)
{
}
protected override void OnConfiguring
(DbContextOptionsBuilder OptionsBuilder)
{
OptionsBuilder.UseSqlServer(@"data source=DESKTOP-JU6B74d\SQL2019;
initial catalog = Laser; integrated security = true;
TrustServerCertificate=True;");
base.OnConfiguring(OptionsBuilder);
}
}
When I use this
dbcontext
, I am not getting the provider error. but in this form, I should repeat my connection string in the db file too.
So when I comment the "
protected override void OnConfiguring
" I get the provider. so how can fix this and only read the connection string from the
appsetting file and why does this problem occur?