We can use an ASP.NET Core Web Application template to create our Web API. We will use Npgsql, a PostgreSQL database provider for Entity Framework Core. Install its package from NuGet with the command below.
PM> Install-Package Npgsql.EntityFrameworkCore.PostgreSQL
If you already have a Postgres database, add its connection string to appsettings.json as PostgreConnection or you can read Installing PostgreSQL and Loading Sample Data post in this series to install a database on your machine.
Write a model for film table of the sample data. Important part is Postgres is case sensitive here, so we need to define column and table names explicitly. Also EF wants to know the identity column of the table.
Now we have our model so we can create our database context like below;
We have to add this context to container in
ConfigureServices function in
Startup class of our web application. Remember to add
Microsoft.EntityFrameworkCore reference to usings.
Congratulations, it is ready to use now. Let the built-in dependency injection of ASP.NET Core to initialize the database context for us in the sample
ValuesController from Web API template.
We will have a list of movie titles as a response.
You can find source code of the project and my notes in olcay/EFCore_Postgres repo.