'Named connection string was not found in application configuration

I added a Startup.cs to my .NET 6 console application as described here. To avoid having to manually specify the connection string when calling Scaffold-DbContext, I tried to provide the connection string from the application configuration like this:

Scaffold-DbContext -Connection name=DatabaseConnectionName -Provider...

For some reason, this does not seem to work and I get the following error:

System.InvalidOperationException: A named connection string was used, but the name 'DatabaseConnectionName' was not found in the application's configuration. Note that named connection strings are only supported when using 'IConfiguration' and a service provider, such as in a typical ASP.NET Core application. See https://go.microsoft.com/fwlink/?linkid=850912 for more information.

Here is the content of my Startup.cs:

public class Startup
{
    IConfiguration Configuration { get; }

    public Startup()
    {
        IConfigurationBuilder builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json");

        Configuration = builder.Build();
    }
    
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddEntityFrameworkNpgsql().AddDbContext<DatabaseContext>(opt =>
            opt.UseNpgsql(Configuration.GetConnectionString("DatabaseConnectionName")));

        services.AddSingleton(Configuration);
    }
}

And this is the content of my appsettings.json:

{
  "ConnectionStrings": {
    "DatabaseConnectionName": "User ID=...;Password=...;Server=...;Port=5432;Database=database-name;Integrated Security=true;Pooling=true"
  }
}

I noticed that this error only occurs while trying to execute the Scaffold-DbContext command, but not when I am running the application normally. I think that this problem might be related to the fact that I am manually creating an instance of the Startup class in my Program.cs, but I don't know if that is true or what I can do about this.

Is there any way how I can fix this error and let the command read the connection string from the configuration file?



Sources

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

Source: Stack Overflow

Solution Source