Introduction
Creating a CRUD (Create, Read, Update, Delete) operation with a PostgreSQL database in an ASP.NET Core Web API is a common task in web development. In this article, we'll walk through the steps to build a Web API using ASP.NET Core, connect it to a PostgreSQL database, and perform CRUD operations on a model named CSharpCornerArticle. We'll also include a real-world use case for this model.
Prerequisites
- Visual Studio or Visual Studio Code (with .NET Core SDK installed)
- PostgreSQL database server installed and running
- Postman or a similar tool for testing the API endpoints
- Let's start by following these steps:
1. Create a new ASP.NET Core Web API project
Open Visual Studio or Visual Studio Code and create a new ASP.NET Core Web API project. You can use the following command in your terminal if you're using Visual Studio Code.

This command will create a new ASP.NET Core Web API project named CSharpCornerApi.
2. Set up the PostgreSQL Database
Ensure you have PostgreSQL installed and running. Create a new database for your project if you haven't already. You can use tools like pgAdmin or the PostgreSQL command line to create a database.
3. Install Entity Framework Core
In your project directory, add Entity Framework Core and Npgsql.EntityFrameworkCore.PostgreSQL packages by running the following commands.
4. Create the Model
Create a model class named CSharpCornerArticle.cs in the Models folder.
5. Configure the Database Context
Create a database context class to configure the connection to the PostgreSQL database.
6. Configure Database Connection
In the appsettings.json file, add your PostgreSQL connection string.
Replace your username and your password with your PostgreSQL credentials.
7. Configure Dependency Injection
In the Startup.cs file, configure dependency injection for the database context.
8. Create CRUD Endpoints
In the Controllers folder, create a controller to handle CRUD operations.
9. Run Migrations
Generate and apply migrations to create the database schema.
Run your ASP.NET Core Web API project, and you can use Postman or any other API testing tool to test the CRUD operations on the CSharpCornerArticle model.
- To create a new article, make a POST request to https://localhost:5001/api/CSharpCornerArticles.
- To retrieve all articles, make a GET request to https://localhost:5001/api/CSharpCornerArticles.
- To retrieve a specific article, make a GET request to https://localhost:5001/api/CSharpCornerArticles/{id}.
- To update an article, make a PUT request to https://localhost:5001/api/CSharpCornerArticles/{id}.
- To delete an article, make a DELETE request to https://localhost:5001/api/CSharpCornerArticles/{id}.
CRUD API with a PostgreSQL database in ASP.NET Core, complete with a real-world use case model named CSharpCornerArticle. You can now build upon this foundation to create more advanced features for your application.