DEV Community

Cover image for Applying Object Relational Mapping (ORM) on a C# .NET application
Raziq Din
Raziq Din

Posted on

Applying Object Relational Mapping (ORM) on a C# .NET application

Hello everyone! In this post , we will go through about ORM implementation on a C#/.NET program, from introduction of ORM concepts all the way to CRUD demonstration.

 

Recently, I’ve been building an indie music player, a Terminal User Interface (TUI) application, since I love minimalistic and lightweight apps. As I worked through the project requirements, I decided to integrate an Object Relational Mapping (ORM) system into my project alongside PostgreSQL to handle database operations more efficiently.

 

While exploring the Microsoft Entity Framework Core documentation
, I discovered that the implementation process is surprisingly straightforward and beginner-friendly!

 

This walkthrough has been simplified to give a clear overview of how ORM works and how to apply it to your .NET project.

 

Below are the libraries you’ll need to add in order to integrate ORM into your .NET development workflow:

 

1. Microsoft.EntityFrameworkCore
This is the main ORM library for C#/.NET projects, This library
provides the core features of Entity Framework, including model
creations and data access in our C#/.NET projects

 
2. Npgsql.EntityFrameworkCore.PostgreSQL
This is our PostgreSQL provider library for Entity Framework Core. It allows our ORM setup to communicate with our PostgreSQL database.

 
3. Microsoft.EntityFrameworkCore.Tools
This library provides useful command-line tools that help in managing migrations, scaffolding, and database updates directly from your terminal. It’s especially handy for generating models and applying schema changes without writing manual SQL commands.

 
Once these packages are installed (either through the NuGet Package Manager in Visual Studio or via the .NET CLI), you’re ready to start setting up your ORM structure!

 

Step 1: Setting Up Your Data Model

Let’s start by creating a simple model class to represent our database entity.
For example, in a music player app, we might have a Song model:

public class Song
{
    public int Id { get; set; } 
    public string Name { get; set; } 
    public string Artist { get; set; } 
    public string Album { get; set; } 
    public int DurationInSeconds { get; set; }
}

Enter fullscreen mode Exit fullscreen mode

This class will serve as our schema for the database table. Entity Framework will map this model to a Songs table in PostgreSQL automatically.

 

Step 2: Creating the Database Context

Next, we’ll define a DbContext, which serves as the bridge between your C# code and the database.

using Microsoft.EntityFrameworkCore;

public class MusicDbContext : DbContext
{
    public DbSet<Song> Songs { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseNpgsql("Host=localhost;Database=musicdb;Username=postgres;Password=yourpassword");
    }
}

Enter fullscreen mode Exit fullscreen mode

The DbSet<Song> represents your table, and the connection string inside OnConfiguring points to your PostgreSQL database. You can change the musicdb to your database name , Username and Password to your own too!

 

Step 3: Running the Initial Migration

After defining your model and context, it’s time to generate and apply the migration to create the database schema.
 
Run these commands in your terminal:


dotnet ef migrations add InitialCreate
dotnet ef database update

Enter fullscreen mode Exit fullscreen mode

migrations add creates a migration file that defines your database structure. InitialCreate can be changed to your desired name of the addition.
database update applies the migration to your PostgreSQL database.

 

Step 4: Performing CRUD Operations

Once your database is ready, you can now perform Create, Read, Update, and Delete operations directly from your C# code using Entity Framework Core.
 

Create (Inserting Data)

using (var db = new MusicDbContext())
{
    var newSong = new Song 
    { 
        Name = "Landslide", 
        Artist = "Fleetwood Mac", 
        Album = "Fleetwood Mac", 
        DurationInSeconds = 220 
    };
    db.Songs.Add(newSong);
    db.SaveChanges();
}

Enter fullscreen mode Exit fullscreen mode

 
Explanation:

  • db.Songs.Add(newSong) tells Entity Framework to add a new record into the Songs table.

  • db.SaveChanges() commits the changes to the database.
    This is how you insert data without writing a single SQL INSERT statement!

 

Read (Retrieving Data)

using (var db = new MusicDbContext())
{
    var songs = db.Songs.ToList();
    foreach (var song in songs)
    {
        Console.WriteLine($"{song.Name} by {song.Artist}");
    }
}

Enter fullscreen mode Exit fullscreen mode

 
Explanation:

  • db.Songs.ToList() retrieves all records from the Songs table and stores them in a list.

  • You can then loop through the results and display or process them as needed.
    This is equivalent to running SELECT * FROM Songs; in SQL.

 

Update (Modifying Data)


using (var db = new MusicDbContext())
{
    var song = db.Songs.FirstOrDefault(s => s.Name == "Landslide");
    if (song != null)
    {
        song.Album = "The Dance";
        db.SaveChanges();
    }
}

Enter fullscreen mode Exit fullscreen mode

 
Explanation:

  • FirstOrDefault searches for the first song record with the name “Landslide.”

  • Once found, we modify its Album property.

  • db.SaveChanges() applies the update automatically in the database.
    This works just like a SQL UPDATE statement, but handled fully in C#.

 

Delete (Removing Data)

using (var db = new MusicDbContext())
{
    var song = db.Songs.FirstOrDefault(s => s.Name == "Landslide");
    if (song != null)
    {
        db.Songs.Remove(song);
        db.SaveChanges();
    }
}

Enter fullscreen mode Exit fullscreen mode

 
Explanation:

  • We fetch the target record first, then call db.Songs.Remove(song) to mark it for deletion.

  • Finally, db.SaveChanges() removes the record permanently from the database.

  • This is equivalent to running DELETE FROM Songs WHERE Name = 'Landslide'; in SQL.

 

Final Thoughts

By using Entity Framework Core, we’ve replaced complex SQL statements with clean, object-oriented C# code. This makes database interactions safer, easier to read, and much more maintainable, especially as your project grows.
 
Whether you’re developing a large-scale enterprise app or a small hobby project like my indie TUI music player, integrating ORM through EF Core can drastically simplify your database workflow.
 
Thank you for reading, do give out your feedback and comments for further improvements of my articles writing! Happy weekend :)

Top comments (0)