Building a .NET Core Web API with Repository Pattern and PostgreSQL
Introduction
In this tutorial, we are going to build a .NET Core Web API application that implements the repository pattern and connects to a PostgreSQL database using Docker. This guide is aimed at beginners, so we'll take it step by step, explaining each part of the process.
Step 1: Setting Up PostgreSQL with Docker
Docker is a tool that allows us to run applications in isolated environments called containers. We'll use Docker to run a PostgreSQL database, which is an advanced open-source relational database.
Docker Compose File: This is a YAML file where we define our PostgreSQL service. The
image: postgres
line tells Docker to use the official PostgreSQL image. We set thePOSTGRES_PASSWORD
environment variable for security, map the port5432
(PostgreSQL default port) to our local machine, and create a volume for data persistence.Run “
docker-compose up -d”
in your terminal in the directory wheredocker-compose.yml
is located. The-d
flag runs it in detached mode, so it doesn't block your terminal.
Step 2: Creating the .NET Core Project
.NET Core is an open-source, cross-platform framework from Microsoft. We use it to build our Web API.
Creating the Project: Use “
dotnet new webapi -n To_Do”
to create a new Web API project.Install Necessary Packages: Your project needs specific NuGet packages to work with Entity Framework Core and PostgreSQL. Add these to your project file (
To_Do.csproj
):Microsoft.EntityFrameworkCore
: The ORM for .NET Core.Microsoft.EntityFrameworkCore.Design
: Design-time tools for Entity Framework Core.Npgsql.EntityFrameworkCore.PostgreSQL
: The PostgreSQL provider for Entity Framework Core.
Here's the XML snippet to include in your
.csproj
file:
Step 3: Defining the Model
A model in .NET Core represents the data in our application. Here, we define a TodoItem
class with Id
and Name
properties.
TodoItem Class: This class represents a todo item in our application. Each todo item has an identifier (
Id
) and aName
.
Step 4: Setting Up the Database Context
The database context (ToDoDbContext
) is part of Entity Framework Core, an Object-Relational Mapper (ORM) that helps us interact with our database using objects.
DbContext: This class lets us query and save data. We define a
DbSet<TodoItem>
to tell Entity Framework that we want to work withTodoItem
objects.
Step 5: Implementing the Repository Pattern
The repository pattern is a design pattern that abstracts data access logic. It makes our code more maintainable and testable.
ITodoRepository Interface: This interface declares the operations (like adding, retrieving, updating, and deleting todo items) that our repository will implement.
TodoRepository Class: This class implements
ITodoRepository
and contains the actual logic to interact with the database using theToDoDbContext
.
Step 6: Configuring Services and Database
In Program.cs
, we set up our application's services and configurations.
Service Configuration: We tell our application to use
ToDoDbContext
with PostgreSQL (configured with the connection string inappsettings.json
) and to useTodoRepository
whenITodoRepository
is required.
Step 7: Creating the Controller
A controller handles HTTP requests and sends responses in a Web API.
TodoController: This class contains methods to handle different HTTP requests (GET, POST, PUT, DELETE) to perform operations on todo items. We use
[Route("api/todo")]
to define the URL path and[ApiController]
to mark it as a controller class.
Step 8: Adding Migrations
Migrations are a way to update the database schema. They track changes in our models and apply these changes to our database.
Running Migrations: We create an initial migration with
“dotnet ef migrations add InitialCreate -o Data/Migrations”
and apply it to our database with “
dotnet ef database update”
.
Step 9: Running the Application
Finally, run your application with “dotnet run”
. Your Web API should now be up and running, able to handle requests and interact with the database.
Source Code on GitHub
The complete source code for this .NET Core 8 Web API project is available on GitHub. You can access it to see the full implementation, clone the repository, and even contribute to it. Here is the link to the repository: To-Do Application on GitHub.
Feel free to explore the code, experiment with it, and use it as a reference for your projects. The repository contains all the necessary files and instructions to get the application up and running on your local machine.