Home > other >  Using appsettings.json for Entity Framework database configuration
Using appsettings.json for Entity Framework database configuration

Time:11-13

I'm using .NET exclusively for Entity Framework's elegant handling of migrations. I have a working project with an EF schema. The part I now need is to move the DB connection string into configuration.

All I have so far is the following:

public partial class EfContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseNpgsql("Host=localhost;Port=5432;Database=...;Username=...;Password=...");
        }
    }
}

There is no other code apart from the entity definitions and migrations (no Startup class or HostBuilder stuff at all).

Can any kind soul instruct me in the simplest way to move the string into appSettings.<env>.json?

CodePudding user response:

Assuming you are using EF Core, then you can use the enter image description here

And you'll need to add the Microsoft.Extensions.Configuration.Json NuGet package.

  • Related