I have a web application in .NET 8 hosted in an Azure web app.
I have added a connection string in environment variables and want to access it in the program.cs file when we normally pass the connection string to the DbContext class:
var services = new ServiceCollection();
builder.Services.AddDbContext<EmployeeDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
I checked the same with copilot, it gave me this code, but it errors at:
builder.Configuration.AddAzureAppConfiguration();
builder.Configuration.Build();
-------------------
using Microsoft.Extensions.Configuration;
var builder = WebApplication.CreateBuilder(args);
// Add Azure App Configuration
builder.Configuration.AddAzureAppConfiguration(Environment.GetEnvironmentVariable("DefaultConnection"));
// Build the configuration
var config = builder.Configuration.Build();
// Access the connection string
string connectionString = config.GetConnectionString("YourConnectionStringName");
Edit
I have also tried this code, but I'm not able to get the connection string:
string connString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<EmployeeDbContext>(options =>
options.UseSqlServer(connString));
Due to this I am getting this error:
An unhandled exception occurred while processing the request. InvalidOperationException: The ConnectionString property has not been initialized.
Microsoft.Data.SqlClient.SqlConnection.PermissionDemand()
Help appreciated


