Introduction: Why does a C# developer need databases?
Any modern application — from a simple blog to a corporate ERP system — stores data. Without a database (DB), it is impossible to ensure persistent storage, fast search, and data integrity. For a C# developer, the ability to work with databases is not just a plus, but a mandatory skill. In this article, we will cover two popular DBMS: relational PostgreSQL and document-oriented MongoDB. You will learn how to connect to them from a .NET application and perform basic operations (CRUD). The article is aimed at beginners, so we will move from installation to the first working code.
1. Environment Setup and Driver Installation
Before writing code, you need to install the databases themselves and add the corresponding NuGet packages to the C# project.
1.1. Installing PostgreSQL and MongoDB
- PostgreSQL: Download the latest version from the official website postgresql.org. During installation, remember the port (default 5432) and the password for the superuser
postgres. - MongoDB: Download the Community Edition from mongodb.com. Install it as a service. For convenience, you can also install MongoDB Compass — a graphical interface for viewing data.
After installation, make sure the services are running. To check, use the command line (for PostgreSQL: psql -U postgres, for MongoDB: mongosh).
1.2. Creating a Project and Installing Packages
Create a .NET 8 console application:
dotnet new console -n DatabaseDemocd DatabaseDemoNow install the necessary drivers:
// For PostgreSQLdotnet add package Npgsql
// For MongoDBdotnet add package MongoDB.DriverNpgsql is a full-featured .NET provider for PostgreSQL. MongoDB.Driver is the official driver from MongoDB, Inc.
2. Working with PostgreSQL in C#
PostgreSQL is an object-relational DBMS. Data is stored in tables linked to each other through foreign keys. For working, we will use raw SQL queries via Npgsql so that you understand the mechanics of connecting and executing commands.
2.1. Connecting to the Server and Creating a Table
First, create a database (e.g., shopdb) via psql or through code. In the code, we will connect to an existing database. Let's write a method to create the Products table:
using Npgsql;
string connectionString = "Host=localhost;Port=5432;Database=shopdb;Username=postgres;Password=your_password";
using var connection = new NpgsqlConnection(connectionString);connection.Open();
string createTable = @"CREATE TABLE IF NOT EXISTS Products ( Id SERIAL PRIMARY KEY, Name VARCHAR(100) NOT NULL, Price DECIMAL(10,2) NOT NULL, Quantity INT DEFAULT 0);";
using var command = new NpgsqlCommand(createTable, connection);command.ExecuteNonQuery();Console.WriteLine("Table created.");Note: we use using to automatically close the connection. The SERIAL type automatically creates an auto-increment field.
2.2. CRUD Operations (Insert, Select, Update, Delete)
Let's add a few products and display them on the screen:
// Inserting datastring insert = "INSERT INTO Products (Name, Price, Quantity) VALUES (@n, @p, @q)";using var cmdInsert = new NpgsqlCommand(insert, connection);cmdInsert.Parameters.AddWithValue("@n", "Laptop");cmdInsert.Parameters.AddWithValue("@p", 79999.99m);cmdInsert.Parameters.AddWithValue("@q", 10);cmdInsert.ExecuteNonQu