What Is Dapper? How To Use Dapper In C#?

Dapper is a straightforward object-relational mapper (ORM) for the Microsoft.NET Framework. It is renowned for its performance and capacity for quick and effective data processing. It is an open-source project that is accessible on GitHub.

Dapper enables developers to interact with data in a manner similar to that of dealing with standard CLR objects (POCOs). As a result, developers won’t need to struggle with difficult data structures like DataSets or DataReaders when handling data; instead, they may use straightforward C# classes.

Dapper’s ability to run raw SQL queries is one of its core characteristics, making it ideal for working with outdated databases or in circumstances where using an ORM is inappropriate. Dapper can map data to a range of data types, including integers, texts, and date/time values, and it also supports stored procedures.

Dapper also has a relatively tiny footprint and little overhead, making it highly lightweight. Because of this, it works well in high-performance applications like online services and mobile apps.

Installing the Dapper NuGet package will let you to begin dealing with data using the Dapper class’s given methods.

For developers searching for a straightforward, lightweight, and high-performance ORM for their.NET projects, Dapper is a wonderful option.

Here is an example of how you could use Dapper to execute a straightforward database query and convert the outcomes to a C# object:

using (var connection = new SqlConnection("Data Source=localhost;Initial Catalog=TestDB;Integrated Security=True"))

    var sql = "SELECT * FROM Customers WHERE CustomerId = @id";
    var customer = connection.Query<Customer>(sql, new { id = 1 }).FirstOrDefault();


In the following example, we’ll demonstrate how to use Dapper’s Query function to run a straightforward SQL query to obtain a single customer from the “Customers” table. Two parameters are sent to the Query method: the SQL query itself and an anonymous object containing the query’s parameter values.

In this scenario, the Customer type is returned by the Query method as an IEnumerable. This example shows how to retrieve the first customer returned by the query using the FirstOrDefault method.

The Customer class, a straightforward POCO with attributes like Name, Address, and Phone, represents a customer.

public class Customer
    public int CustomerId { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }

This is only a simple illustration of how you can use Dapper to execute database queries and convert the outcomes into C# objects. Dapper offers a variety of additional techniques and capabilities that help you carry out more difficult tasks like dealing with stored procedures, adding, updating, and removing data, among others.

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories