I needed a way to switch a new ASP.NET Core Web App (MVC)
create with Authentication Type
of Individual Accounts
over to use PostgreSQL. Microsoft ship the template to use MS SQL, I mean why would they not push their own product 😂
Inital Steps
- Create the Solution and Project, I normally just create using VS 2022 but it can be done in the CLI
1 | dotnet tool install --global dotnet-aspnet-codegenerator |
- Install EntityFrameworkCore for PostgreSQL
1 | cd MyPostgresWebApp |
- Update Program.cs to configure the application to use PostgreSQL instead of SQL Server.
1 | // before |
- Update
DbContext
to set the schema
1 | // Data/ApplicationDbContext.cs |
- Update the connection string in
appsettings.json
, generally I delete theConnectionStrings:DefaultConnection
node fromappsettings.json
and just add my local connection string toappsettings.Development.json
as I inject the production connection string when deploying, normally with Github Actions because its amazing and TeamCity & Octpus Deploy are just too complicated for my brain ❤️
1 | // before |
- Spin up a docker postgresql instance, cool kids use docker right? Generally its best practice to follow principle of least privlage, so
my_webapp_user
should not be the admin user as Im creating it here, this doesnt matter too much for local but in productionm systems you should have aadmin_user
with full access to the db,schema manager
which can create tables/schemas for migration, andwebapp user
which does basic CRUD from the WebApp/Api
1 | docker run --name salestracker_db -p 5432:5432 -e POSTGRES_USER=my_webapp_user -e POSTGRES_PASSWORD=00000000-0000-0000-0000-000000000001 -e POSTGRES_DB=psc_db -v "$(pwd)/initialize-database.sql:/docker-entrypoint-initdb.d/initialize-database.sql" -d postgres:17.2 |
Also here initialize-database.sql
is a basic bootstrap script like
1 | CREATE SCHEMA my_schema; |
Clear old migrations that may have been created with the old
MS SQL
provider, for me there were in\Data\Migrations\
Create new migration, for me this was created in the root of my app in
\Migrations\
and I ran the command in the context of the.csproj
file
1 | dotnet ef migrations add InitialCreate # Add a new migration (this creates the migration files) |
- Apply the migration
1 | dotnet ef database update # Apply the migration to your PostgreSQL database |
- Check the data
The migration history will be in the public schema
1 | SELECT "MigrationId", "ProductVersion" |
The actual migration tables will be in the my_schema
set in step 3.
Future Migrations
Future entity first migrations can then be applied.
Create the entity
Apply
DbSet
and anymappings
the same as step 3 in MySQL with Entity Framework CoreCreate the migration the same as step 8 in this post, dont call it
InitialCreate
, use something related to your changeApply the migration with the update command the same as step 9 above
Check the data the same as step step 10 above.
That should get you rocking EF Core with PostgreSQL.