Setup a PostgreSQL connection with Entity Framework in .NET 7
Thanks to Npgsql it is very easy to setup your .NET 7 project with your PostgreSQL database. In this article I will provide the code for setting up the connection and also create a table in your PostgreSQL database using Entity Framework.
Before we can start coding anything, we need to install 3 NuGet Packages. You will have to install following:
- Microsoft.EntityFrameworkCore
- Microsoft.EntityFrameworkCore.Tools
- Npgsql.EntityFrameworkCore.PostgreSQL
Because we use .NET 7, all the NuGet Packages also need to be the latest 7.x.x version that your can get. In that way you make sure it works with .NET 7.
Setup the DbContext file
In my case I have created a AppDbContext.cs file inside my a folder called "Data". You can call both the file and the folder what ever you want. Just that the file inherits from the DbContext class from the Entity Framework NuGet Package.
The connection string will come from the appsettings.json file and in this case target the WebApiDatabase string. You can again call it a more saying name for your project.
The code inside the AppDbContext file will look like this:
In this case I have a host that is my localhost, a database called Company and a username and password that is postgres and 1234. The appsettings.json file:
In the AppDbContext I specify a DbSet that is set to a Model called Employee that when we migrate will create the table Employees.
In my case I have set the context file into a folder called Data. And I also created a folder for my Employees model called Model.
Migrate the model
To check the connection you can go and migrate the table. So in the Package Manager Console go and first run the Add-Migration command to create the migration file, and next go and Update-Database to make the changes in the database.