Reverse Engineer Postgres Database Model Using EntityFramework Core

reverse engineer data model from postgres db

Arjun Krishna

2 minute read

I tried Dapper it was fun to use. It is pretty powerful. I now wanted to try entityframework-core. In Dapper, I did everything in database first. Now I wanted to do everything in code first. I’ve used entityframework earlier in my previous jobs so have an understanding how it works but there is always something new to learn.

I’ve this side project (parents life app) where I use blazor wasm along with identity server 4, grpc-web, hangfire, alexa integration (kinda broken at this time) with postgres as backend. Learned about Azure DevOps, Azure App Service and pricing structure that works for me as an Individual developer. Most of the samples I read for blazor wasm with code first front-end validation are using ef-core and poco objects directly (I’ve added grpc into the mix and not going to be using poco directly in the front-end, so lets see how it works out for me :)). I thought let me migrate to it to lessen the friction, otherwise the 2 hours a week (if I am lucky) I spend on it goes in trying to fix other dapper/grpc-web related issues. I just want a streamlined easy to integrate side project where I can focus on adding features and not waste time on integration issues :). I generally use Sql Server with Redgate’s Sql Prompt plugin, so Postgres’s sql syntax and typing queries without such productivity tools was slowing me down and I do not want to lose motivation on this side project, I want to build momentum.

I found a nice article with step-by-step instructions to reverse engineer models from postgres db. I like small scripts that I can use later so pasting it below. Over the years I’ve realized there is no point remembering such things, just remember that there is such a capability. Maybe in the future even that will also be not needed. You just need to ask Alexa or whatever AI assistant tool is available to you.

The following script generates the models and other wiring code that can be copied to you main project.

dotnet new console
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.Tools.DotNet
dotnet add package Microsoft.NETCore.App
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL.Design
dotnet tool install --global dotnet-ef
dotnet ef dbcontext scaffold "Server=hostNameGoesHere;Port=5432;Database=dbNameGoesHere;User Id=userIdGoesHere;Password=pwdGoesHere;sslmode=Require;Trust Server Certificate=true;" Npgsql.EntityFrameworkCore.PostgreSQL -o Models