Working with Databases in C#: PostgreSQL and MongoDB for Beginners

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction to Working with Databases in C#

\n\n

In modern application development, working with databases is one of the key skills. C# (.NET) provides powerful tools for interacting with both relational (PostgreSQL) and document-oriented (MongoDB) databases. In this article, we will cover the basics of connecting and performing CRUD operations for both systems.

\n\n

The article is intended for beginner developers familiar with the basics of C#. We will look at both the traditional approach via SQL queries (Npgsql) and the modern ORM — Entity Framework Core, as well as working with MongoDB through the official driver.

\n\n

1. Working with PostgreSQL in C#

\n\n

PostgreSQL is a powerful open-source relational DBMS. To work with it in .NET, the Npgsql package or Entity Framework Core with the Npgsql.EntityFrameworkCore.PostgreSQL provider is used.

\n\n

1.1 Connection via Npgsql (low-level access)

\n\n

Install the package via NuGet:

\n\n
dotnet add package Npgsql
\n\n

Example of a simple connection and query execution:

\n\n
using Npgsql;\n\nstring connectionString = "Host=localhost;Port=5432;Database=mydb;Username=user;Password=pass";\n\nusing var conn = new NpgsqlConnection(connectionString);\nconn.Open();\n\nstring sql = "SELECT id, name, age FROM users WHERE age > @minAge";\nusing var cmd = new NpgsqlCommand(sql, conn);\ncmd.Parameters.AddWithValue("minAge", 18);\n\nusing var reader = cmd.ExecuteReader();\nwhile (reader.Read())\n{\n    Console.WriteLine($"ID: {reader["id"]}, Name: {reader["name"]}, Age: {reader["age"]}");\n}
\n\n

1.2 Using Entity Framework Core with PostgreSQL

\n\n

Install the packages:

\n\n
dotnet add package Microsoft.EntityFrameworkCore\ndotnet add package Npgsql.EntityFrameworkCore.PostgreSQL
\n\n

Create a model and context:

\n\n
public class User\n{\n    public int Id { get; set; }\n    public string Name { get; set; }\n    public int Age { get; set; }\n}\n\npublic class AppDbContext : DbContext\n{\n    public DbSet<User> Users { get; set; }\n\n    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)\n    {\n        optionsBuilder.UseNpgsql("Host=localhost;Database=mydb;Username=user;Password=pass");\n    }\n}
\n\n

CRUD operations via EF Core:

\n\n
using var db = new AppDbContext();\n\n// Create\ndb.Users.Add(new User { Name = "Anna", Age = 25 });\ndb.SaveChanges();\n\n// Read\nvar users = db.Users.Where(u => u.Age > 20).ToList();\n\n// Update\nvar user = db.Users.First();\nuser.Age = 30;\ndb.SaveChanges();\n\n// Delete\ndb.Users.Remove(user);\ndb.SaveChanges();
\n\n

2. Working with MongoDB in C#

\n\n

MongoDB is a NoSQL database that stores data in BSON document format. The official MongoDB.Driver driver is used for C#.

\n\n

2.1 Installation and connection setup

\n\n

Install the package:

\n\n
dotnet add package MongoDB.Driver
\n\n

Connecting to a local MongoDB server:

\n\n
using MongoDB.Driver;\n\nvar client = new MongoClient("mongodb://localhost:27017");\nvar database = client.GetDatabase("mydb");\nvar collection = database.GetCollection<BsonDocument>("users");
\n\n

2.2 CRUD operations with MongoDB

\n\n

Create a model class:

\n\n
public class User\n{\n    public MongoDB.Bson.ObjectId Id { get; set; }\n    public string Name { get; set; }\n    public int Age { get; set; }\n}
\n\n

Example of working with a collection:

\n\n
var collection = database.GetCollection<User>("users");\n\n// Create\nvar newUser = new User { Name = "Ivan", Age = 30 };\ncollection.InsertOne(newUser);\n\n// Read\nvar filter = Builders<User>.Filter.Eq(u => u.Name, "Ivan");\nvar user = collection.Find(filter).FirstOrDefault();\n\n// Update\nvar update = Builders&l                

Blogs

Book Recommendations