Getting Started with Dapper in C#

When building data-driven applications in .NET, developers often face a trade-off between performance and productivity. Full-fledged Object-Relational Mappers (ORMs) like Entity Framework (EF) offer convenience and abstraction but can introduce overhead in performance-critical scenarios. This is where Dapper.

In this post, we’ll explore what Dapper is, how it works, and why it’s a great choice for developers who want speed and simplicity in data access.

Getting Started with Dapper in C#: The Lightweight ORM for .NET Developers

Getting Started

Developers often have to walk a fine line between convenience and performance when building .NET applications. Full-blown ORMs like Entity Framework make working with databases super easy, but that ease can come at the cost of speed because of all the abstraction happening behind the scenes. On the flip side, writing raw SQL gives you total control and top-notch performance—but also a ton of repetitive, boilerplate code.

That’s where Dapper comes in. It hits the sweet spot between power and simplicity. As a lightweight ORM, Dapper gives you the performance of raw SQL with the ease and readability of an ORM, which is exactly why so many C# developers love using it.

What Is Dapper?

Dapper is a simple, lightweight and open-source micro ORM (Object Relational Mapper) developed by the team at Stack Overflow. It extends the functionality of the IDbConnection interface in .NET to make working with SQL queries and mapping results to C# objects extremely simple.

Unlike Entity Framework or NHibernate, Dapper doesn’t generate SQL for you. You write the SQL yourself, but Dapper efficiently maps the results to your C# classes.

Key Features
  • Performance: Nearly as fast as raw ADO.NET due to minimal abstraction.
  • Lightweight: Only a few files and a single DLL (no complex setup).
  • Simple API: Intuitive methods like Query, QueryFirst, and Execute.
  • Flexible: Works with any database supported by ADO.NET (SQL Server, MySQL, PostgreSQL, SQLite, etc.).
  • POCO Mapping: Automatically maps query results to Plain Old CLR Objects (POCOs).

Why Use Dapper?

Here are some reasons developers choose Dapper:
  1. Speed and Efficiency: Dapper is known for being one of the fastest ORMs for .NET. It’s only slightly slower than using raw ADO.NET commands directly.
  2. Simplicity: Dapper has a small learning curve. You write your own SQL queries, so you maintain full control over the database layer.
  3. Lightweight: There’s no complex configuration or entity tracking. You just install the NuGet package and start using it.
  4. Compatibility: Dapper works with any database supported by ADO.NET (SQL Server, PostgreSQL, MySQL, SQLite, etc.).

Installing Dapper

You can install Dapper via NuGet Package Manager in Visual Studio or via the .NET CLI:
dotnet add package Dapper

Note:- If you want to know how to install NuGet package, then visit this post "Installing NuGet Packages: A Beginner's Guide".

Basic Usage Example of Dapper in C#

Let’s look at a simple example to understand how Dapper works.

Create a Model Class
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Position { get; set; }
}

Create a Database Connection
using System.Data.SqlClient;
using Dapper;
string connectionString = "Server=.;Database=MyCompany;Trusted_Connection=True;";
using var connection = new SqlConnection(connectionString);

Query Data
var employees = connection.Query<Employee>("SELECT * FROM Employees").ToList();
foreach (var emp in employees)
{
  Console.WriteLine($"{emp.Name} - {emp.Position}");
}

Query with Parameters
string query = "SELECT * FROM Employees WHERE Position = @Position";
var developers = connection.Query<Employee>(query, new { Position = "Developer" }).ToList();

Insert, Update, and Delete
// Insert
string insertQuery = "INSERT INTO Employees (Name, Position, Salary) VALUES (@Name, @Position, @Salary)";
connection.Execute(insertQuery, new { Name = "Jane Doe", Position = "Developer", Salary = 70000 });
// Update
string updateQuery = "UPDATE Employees SET Salary = @Salary WHERE Id = @Id";
connection.Execute(updateQuery, new { Id = 1, Salary = 80000 });
// Delete
string deleteQuery = "DELETE FROM Employees WHERE Id = @Id";
connection.Execute(deleteQuery, new { Id = 2 });

Advanced Features

Multiple Mapping
string sql = @"SELECT e.*, d.* FROM Employees e
INNER JOIN Departments d ON e.DepartmentId = d.Id";
var result = connection.Query<Employee, Department, Employee>(
sql,
(employee, department) => { employee.Department = department; return employee; }
);

Stored Procedures
var result = connection.Query<Employee>(
"GetAllEmployees",
commandType: CommandType.StoredProcedure
);

When to Use Dapper

Use Dapper if:
  • You prefer writing SQL manually.
  • You want high performance data access.
  • You’re building microservices or small-to-medium apps where simplicity matters.
Avoid Dapper if:
  • You need complex change tracking, lazy loading, or migrations — features better suited for Entity Framework./li>

Summary

Dapper is an excellent choice for developers who want the performance of raw SQL combined with the convenience of object mapping. It’s simple, fast, and gives you full control over your queries which making it perfect for applications that demand both speed and maintainability.

Thanks

Kailash Chandra Behera

I am an IT professional with over 13 years of experience in the full software development life cycle for Windows, services, and web-based applications using Microsoft .NET technologies.

Previous Post Next Post

نموذج الاتصال