Introduction to Working with Databases in C#
\n\nIn 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\nThe 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\n1. Working with PostgreSQL in C#
\n\nPostgreSQL 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.
1.1 Connection via Npgsql (low-level access)
\n\nInstall the package via NuGet:
\n\ndotnet add package Npgsql\n\nExample of a simple connection and query execution:
\n\nusing 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\n1.2 Using Entity Framework Core with PostgreSQL
\n\nInstall the packages:
\n\ndotnet add package Microsoft.EntityFrameworkCore\ndotnet add package Npgsql.EntityFrameworkCore.PostgreSQL\n\nCreate a model and context:
\n\npublic 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\nCRUD operations via EF Core:
\n\nusing 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\n2. Working with MongoDB in C#
\n\nMongoDB is a NoSQL database that stores data in BSON document format. The official MongoDB.Driver driver is used for C#.
2.1 Installation and connection setup
\n\nInstall the package:
\n\ndotnet add package MongoDB.Driver\n\nConnecting to a local MongoDB server:
\n\nusing MongoDB.Driver;\n\nvar client = new MongoClient("mongodb://localhost:27017");\nvar database = client.GetDatabase("mydb");\nvar collection = database.GetCollection<BsonDocument>("users");\n\n2.2 CRUD operations with MongoDB
\n\nCreate a model class:
\n\npublic 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\nExample of working with a collection:
\n\nvar 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