Getting Started With PostgreSQL Using Dapper In .NET Core

PostgreSQL is a powerful, open source object-relational database system that is very easy to use. Dapper is a high performance micro-ORM, which is my favorite.

Now, I will show you how to use this combination in .NET Core.

Requirement

  • Npgsql 3.1.9
  • Dapper 1.50.2

My Environment

  • Visual Studio 2015 Community with update 3
  • PostgreSQL 9.6
  • pgAdmin 4

Demonstration

Step 1

Create a new table in pgAdmin

Step 2

Create a new Console Application (.NET Core).

Edit the project.json

After saving the file, it will restore automatically and you can see the references as follow:

image0012

Step 3

Create a new class, Customer.cs, mapping to the table customer.

Step 4

Now, we will use Dapper to operate the PG database.

Insert

After running the above code, we will get the message “inserted successfully!” and get the customer’s first name and his email.

Methods OpenConnection and PrintData are as follow.

Update

After running the above code, we will get the message “updated successfully!” and get the customer’s first name and his new email.

Delete

After running the above code, we will get the message “deleted successfully!” and “the table is empty!”

Here is the result!

image0022

Summary

There are many combinations we can use during our dev times in .NET Core, such as EF Core + MS SQLServer, EF Core + SQLite, Dapper + MS SQL Server etc.