'ASP.NET Core 6 named connection string not found

I am using .NET 6 and Entity Framework Core 6 in a new ASP.NET Core MVC web app. I have my connection string set in user-secrets. I was able to perform a

dotnet ef dbcontext scaffold Name=ConnectionStrings:someconn 

without any trouble. My model context was created. Now I want to do a simple query, but the builder in program.cs is complaining about not finding the connection.

Here I create a builder

var builder = WebApplication.CreateBuilder(args);

var currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
var environmentName = builder.Environment.EnvironmentName;

builder.Configuration
    .SetBasePath(currentDirectory)
    .AddUserSecrets<Program>()
    .AddEnvironmentVariables();

var connectionString = builder.Configuration.GetConnectionString("ConnectionStrings:someconn ");

Here I place this code inside program.cs, and just before app.Run.

using (var ctx = new ModelContext())
{
    List<SomeModel> pd = ctx.SomeModel
        .Where(p => p.Id == "12345").ToList();

}

app.Run();

Error

A named connection string was used, but the name 'ConnectionStrings:someconn' was not found in the application's configuration



Solution 1:[1]

Here's a sample for reading a connection string from appsettings.json. (for simplicity I've used a sample for sqlite, which shouldn't affect they general way of reading the string.)

Hope this helps.

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Information",
      "Microsoft.AspNetCore": "Information"
    }
  },
  "ConnectionStrings": {
    "someconn": "Data Source=some.sqlite"
  }
}

and the in Program.cs

var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("someconn")

A reason could be that the appsettings.json isn't found. Maybe check if this part of the code is needed or execute it after reading the connection string.

var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("someconn")


var currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
var environmentName = builder.Environment.EnvironmentName;

builder.Configuration
    .SetBasePath(currentDirectory)//check if this is necessary
    .AddUserSecrets<Program>()
    .AddEnvironmentVariables();

Solution 2:[2]

Change below code

var connectionString = builder.Configuration.GetConnectionString("ConnectionStrings:someconn ");

to

var connectionString = builder.Configuration.GetConnectionString("someconn");

It works in my local, you can try it. Also note that there is an extra space in your code.

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Jason