DEV Community

Hassan BOLAJRAF
Hassan BOLAJRAF

Posted on

C# | Dapper Using Stored Procedures

Note
You can check other posts on my personal website: https://hbolajraf.net

Introduction

Dapper is a simple, lightweight Object-Relational Mapping (ORM) library for .NET. It is designed to provide high performance and reduce the overhead typically associated with traditional ORMs. One of the powerful features of Dapper is its support for executing stored procedures. In this guide, we will explore how to use stored procedures in C# with Dapper.

Prerequisites

Before getting started, make sure you have the following installed:

  • Dapper NuGet package
  • SQL Server or another database with a stored procedure to work with

Example: Basic Setup

using System;
using System.Data;
using System.Data.SqlClient;
using Dapper;

class Program
{
    static void Main()
    {
        // Connection string for your database
        string connectionString = "YourConnectionStringHere";

        using (IDbConnection dbConnection = new SqlConnection(connectionString))
        {
            // Example of calling a stored procedure with Dapper
            var result = dbConnection.Query<int>("YourStoredProcedureName", commandType: CommandType.StoredProcedure);

            // Process the result as needed
            foreach (var value in result)
            {
                Console.WriteLine(value);
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, replace YourConnectionStringHere with your actual database connection string and YourStoredProcedureName with the name of your stored procedure.

Example: Stored Procedure with Parameters

using System;
using System.Data;
using System.Data.SqlClient;
using Dapper;

class Program
{
    static void Main()
    {
        string connectionString = "YourConnectionStringHere";

        using (IDbConnection dbConnection = new SqlConnection(connectionString))
        {
            // Parameters for the stored procedure
            var parameters = new { Param1 = "Value1", Param2 = 42 };

            // Example of calling a stored procedure with parameters using Dapper
            var result = dbConnection.Query<int>("YourStoredProcedureName", parameters, commandType: CommandType.StoredProcedure);

            foreach (var value in result)
            {
                Console.WriteLine(value);
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, define the parameters for your stored procedure and replace Value1 and 42 with the actual values.

What Next?

Dapper makes working with stored procedures in C# straightforward. It provides a clean and efficient way to interact with databases using a minimal amount of code. Experiment with the provided examples and adapt them to your specific use case to leverage the power of Dapper in your C# projects.

Top comments (0)