Power of Dapper in .Net Core

Introduction

In .NET development, managing data access efficiently and effectively is crucial for creating high-performance applications. While Entity Framework is a popular choice for Object-Relational Mapping (ORM) in .NET, it can sometimes be overkill for simple scenarios or performance-critical applications. This is where Dapper comes into play. Dapper is a lightweight ORM developed by the team at Stack Overflow, and it provides a simple and efficient way to interact with databases in .NET Core applications. In this article, we will explore the uses of Dapper, demonstrate its advantages, and provide a simple code snippet along with sample output to illustrate its usage.

Dapper

Dapper is an open-source, micro ORM that provides fast and flexible data access in .NET applications. Unlike full-fledged ORMs like Entity Framework, Dapper focuses on performance and simplicity. It allows developers to execute SQL queries directly and map the results to strongly typed objects, making it a perfect choice for scenarios where you need fine-grained control over SQL execution and performance.

Advantages of Using Dapper

  • Performance: Dapper is known for its speed and efficiency. It is often cited as one of the fastest ORMs available for .NET, making it ideal for performance-critical applications.
  • Simplicity: Dapper is easy to set up and use. Its API is straightforward, and it requires minimal configuration.
  • Flexibility: Dapper allows developers to write raw SQL queries, giving them full control over the database interactions. This flexibility is particularly useful when dealing with complex queries or custom SQL logic.
  • Lightweight: Dapper is lightweight and does not impose a heavy footprint on your application. It integrates seamlessly with existing .NET Core applications without adding unnecessary overhead.

Setting Up Dapper in .NET Core

To demonstrate the usage of Dapper, we will create a simple .NET Core console application that interacts with a SQLite database.

Step 1. Create a New .NET Core Project.

Open your terminal or command prompt and run the following command to create a new .NET Core console application.

dotnet new console -n DapperExample  
cd DapperExample

Step 2. Install Dapper and SQLite Packages.

Next, we need to install the Dapper and SQLite packages.

dotnet add package Dapper  
dotnet add package Microsoft.Data.Sqlite

Dapper in .NET Core

Now that we have set up our project, let's write some code to interact with the database using Dapper.

Step 3. Create a Data Model.

Create a new file named Product.cs and add the following code to define the Product class.

public class Product  
{  
    public int Id { get; set; }  
    public string Name { get; set; }  
    public decimal Price { get; set; }  
}

Step 4. Create a Database Helper Class.

Create a new file named DatabaseHelper.cs and add the following code to create a helper class for database interactions.

using System.Data;  
using Microsoft.Data.Sqlite;  
using Dapper;  

public class DatabaseHelper  
{  
    private readonly string _connectionString;  

    public DatabaseHelper(string connectionString)  
    {  
        _connectionString = connectionString;  
    }  

    public IDbConnection GetConnection()  
    {  
        return new SqliteConnection(_connectionString);  
    }  
}

Step 5. Write Code to Interact with the Database.

In the Program.cs file, add the following code to create and populate the database, and query data using Dapper.

using System;  
using System.Collections.Generic;  

class Program  
{  
    static void Main(string[] args)  
    {  
        string connectionString = "Data Source=products.db";  
        DatabaseHelper dbHelper = new DatabaseHelper(connectionString);  

        using (var connection = dbHelper.GetConnection())  
        {  
            connection.Open();  

            // Create table  
            string createTableQuery = @"
                CREATE TABLE IF NOT EXISTS Products (
                    Id INTEGER PRIMARY KEY AUTOINCREMENT,
                    Name TEXT NOT NULL,
                    Price REAL NOT NULL
                )";  
            connection.Execute(createTableQuery);  

            // Insert data  
            string insertQuery = "INSERT INTO Products (Name, Price) VALUES (@Name, @Price)";  
            connection.Execute(insertQuery, new Product { Name = "Laptop", Price = 999.99m });  
            connection.Execute(insertQuery, new Product { Name = "Smartphone", Price = 499.99m });  

            // Query data  
            string selectQuery = "SELECT * FROM Products";  
            IEnumerable<Product> products = connection.Query<Product>(selectQuery);  

            // Display data  
            foreach (var product in products)  
            {  
                Console.WriteLine($"Id: {product.Id}, Name: {product.Name}, Price: {product.Price}");  
            }  
        }  
    }  
}

Sample Output

When you run the application, you should see the following output.

Sample Output

Conclusion

Dapper is a powerful and lightweight ORM that provides a simple and efficient way to interact with databases in .NET Core applications. Its performance, simplicity, and flexibility make it an excellent choice for scenarios where you need fine-grained control over SQL execution.

Up Next
    Ebook Download
    View all
    Learn
    View all