I should point out I'm new to .NET...
I have the following appsettings.json file:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"MyContext": "Host=localhost;Database=test;Username=user;Password=''"
}
}
In the MyContext.cs file I want to read the connection string from the appsettings.json config:
using Microsoft.EntityFrameworkCore;
using System;
using System.Configuration;
namespace My.Models
{
public partial class MyContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
Console.WriteLine(ConfigurationManager.ConnectionStrings.Count);
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseNpgsql(ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString);
}
}
}
But ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString is null, any ideas why?
I'm using the config file successfully in Startup.cs via Configuration.GetConnectionString("MyContext"), but here I want to read the connection string from this config for situations outside of the ASP.NET application (i.e. in EF migrations I want to do using var db = new MyContext();), but have no idea why the above is returning null.
Is ConfigurationManager not reading from my appsettings.json file? Not sure how to tell, as ConfigurationManager.ConnectionStrings.Count returns 1, so I'm pretty confused. Is there anything obviously wrong someone can see?
I'm using .NET Core 5 and EF Core version 5