Reputation: 166
When trying to register a database context in startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(option => option.EnableEndpointRouting = false);
services.AddDbContext<PostDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("PostDbContext")));
}
I get error
The name "Configuration" does not exist in the current context.
All code examples are taken from the official Microsoft documentation. Tutorials -> MVC -> Get started -> Add model. ASP.NET Core version: 3.1 How fix it?
Upvotes: 2
Views: 6989
Reputation: 1
I think the best way to deal with this problems is Add "builder" before every "Services" u want to build in Program in .NetCore6
Upvotes: 0
Reputation: 173
If you are using dotnet 6 and the above solution no longer applies because they got rid of the startup file... try the below answer.
Configuration.GetConnectionString(string connName) in .NET6 is under builder:
var builder = WebApplication.CreateBuilder(args);
string connString = builder.Configuration.GetConnectionString("DefaultConnection");
also AddDbContext() is under builder.Services:
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
I hope it helps.
Upvotes: 3
Reputation: 11
This problem occurs because you have not defined Configuration which is an instance of IConfiguration interface like this-
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
Here Configuration is important to define which checks configuration details. For Ex.-Configuration.GetConnectionString("Your Connection String") checks the connection string from appsettings.json file to get or set data in database.
Upvotes: 0
Reputation: 166
I have not defined a configuration.
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
Upvotes: 2