Previous lesson: 🧱 Lesson 4 - Adding SQL Server Support (Multi-Database Setup)
🚀 Introduction
PostgreSQL is a powerful open-source database widely used in enterprise and cloud systems.
In multi-tenant or SaaS environments, it’s common to support multiple database providers (e.g., MySQL, SQL Server, PostgreSQL) based on customer or deployment needs.
Our goal today:
🐳 Pull and run PostgreSQL via Docker
⚙️ Add PostgreSQL support in EF Core
🏗️ Create PostgresDbContext and design-time factory
🧱 Run migrations and verify setup
🐳 Step 1. Pull PostgreSQL Docker Image and Run Container
Let’s start by running PostgreSQL locally inside Docker.
docker pull postgres
Run container
docker run -d --name postgres -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=Admin123! -p 5432:5432 postgres:latest
⚙️ Step 2. Update appsettings.json
Add a new connection string for PostgreSQL in your ECommerce.API project.
"PostgreSQL":"Host=localhost;Port=5432;Database=ECommerceDb;Username=postgres;Password=Admin123!",Now your application can dynamically choose the provider by changing:
"DatabaseProvider": "PostgreSQL"
🧱 Step 3. Create PostgreSQL DbContext
Path : ECommerce.Infrastructure/Data/PostgresDbContext.cs
using Microsoft.EntityFrameworkCore;
namespace ECommerce.Infrastructure.Data;
public class PostgresDbContext : AppDbContext
{
public PostgresDbContext(DbContextOptions<PostgresDbContext> options)
: base(options)
{
}
}
Install Package
dotnet add ECommerce.Infrastructure package Npgsql.EntityFrameworkCore.PostgreSQL --version 8.0.11🧩 Step 5. Add Design-Time Factory
EF Core CLI needs this factory for dotnet ef migrations when it can’t build the host automatically.
Create PostgresDbContextFactory
Path : ECommerce.Infrastructure/Data/PostgresDbContextFactory.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
namespace ECommerce.Infrastructure.Data;
public class PostgresDbContextFactory : IDesignTimeDbContextFactory<PostgresDbContext>
{
public PostgresDbContext CreateDbContext(string[] args)
{
var basePath = Path.Combine(Directory.GetCurrentDirectory(), "../ECommerce.API");
var configuration = new ConfigurationBuilder()
.SetBasePath(basePath)
.AddJsonFile("appsettings.json", optional: false)
.AddJsonFile("appsettings.Development.json", optional: true)
.Build();
var connectionString = configuration.GetConnectionString("PostgreSQL");
var optionsBuilder = new DbContextOptionsBuilder<PostgresDbContext>();
optionsBuilder.UseNpgsql(connectionString);
return new PostgresDbContext(optionsBuilder.Options);
}
}










Join the conversation! Your thoughts help the community grow.