Search code examples
.netentity-frameworknpgsql

npgsql configure __EFMigrationHistoryTable from appsettings.json


I am currently migrating my .net application to PostgreSQL 15. Thus, I need to move all my tables from the public schema to a custom schema.

My __EFMigrationHistory table, also needs to be moved to the custom schema.

I have found the following way of controlling this:

services.AddDbContext<ApplicationDbContext>(options =>
    options.UseNpgsql(
        Configuration.GetConnectionString("DefaultConnection"),
        x => x.MigrationsHistoryTable("__MyMigrationsHistory", "not-public")));

However, we configure our UseNpgsql() from the appsettings.json file. Something along the lines of:

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

private IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<DataContext>(options =>
    {
        options.UseNpgsql(Configuration);
    });
}

While our appsettings.json looks as follows:

"Postgres": {
   "Client": {
        "Server": "localhost",
        "Port": "5433",
        "Database": "mydatabase",
        "Username": "xxx",
        "Password": "xxx",
        "Include Error Detail": true
    }
},

Is it possible to configure this in the appsettings.json file? If yes, how?


Solution

  • For now, I will construct my connection string manually and then use an overload that allows setting a connection string and configuring the `` `__EFMigrationHistoryTable``` together.

    var host = Configuration.GetValue<string>("Postgres:Client:Server");
    var port = Configuration.GetValue<string>("Postgres:Client:Port");
    var user = Configuration.GetValue<string>("Postgres:Client:Username");
    var pass = Configuration.GetValue<string>("Postgres:Client:Password");
    var database = Configuration.GetValue<string>("Postgres:Client:Database");
    
    var connectionString = $"Host={host};Port={port};Username={user};Password={pass};Database={database};";
    
    options.UseNpgsql(
        connectionString,
        o =>
        {
            o.MigrationsHistoryTable("__EFMigrationHistory", "data");
        });