Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. Dapper
  4. How to Use Stored Procedures with Parameters in Dapper

How to Use Stored Procedures with Parameters in Dapper

Date- Jan 23,2024 Updated Mar 2026 5450 Free Download Pay & Download
Dapper stored procedures

Understanding Dapper and Stored Procedures

Dapper is a simple yet powerful micro-ORM for .NET that enables developers to work with databases in a more streamlined manner. Unlike traditional ORMs, Dapper focuses on performance and simplicity, allowing developers to execute SQL queries and map results directly to objects. Stored procedures, on the other hand, are precompiled SQL statements that reside in the database and can be executed with parameters. They encapsulate business logic and can improve performance by reducing network traffic and execution time.

Using stored procedures with Dapper allows developers to leverage the best of both worlds: the performance and security of stored procedures combined with the ease of use of Dapper. This method is particularly useful in enterprise applications where complex queries and data manipulation are common.

Prerequisites

Before diving into the implementation, ensure you have the following prerequisites:

  • A basic understanding of C# and .NET programming.
  • Familiarity with SQL and relational databases.
  • Visual Studio or any C# development environment set up with access to a SQL Server database.
  • The Dapper NuGet package installed in your project.

Setting up the SqlConnection

Establishing a connection to the database is the first step in using Dapper with stored procedures. The SqlConnection class from the System.Data.SqlClient namespace is used to create a connection. Ensure that the connection string is correctly configured to point to your database.

using (var connection = new SqlConnection(connectionString)) {
    connection.Open();
    // Additional code will go here
}

In this code, we open a connection to the database using the provided connection string. Always ensure to wrap the connection in a using statement to properly dispose of the connection once it is no longer needed, preventing any resource leaks.

Setting up Parameters with DynamicParameters

Dapper provides the DynamicParameters class to facilitate the passing of parameters to stored procedures. This class allows for easy addition of parameters with various data types, making it flexible for different scenarios.

DynamicParameters parameters = new DynamicParameters();
parameters.Add("id", 1); // Adding a parameter 'id' with a value of 1

In this example, we create an instance of DynamicParameters and add a parameter named id with a value of 1. You can add multiple parameters as needed, ensuring that their names match those defined in your stored procedure.

Executing the Stored Procedure

Once the parameters are set up, you can execute the stored procedure using Dapper's QuerySingleOrDefault method. This method is ideal for scenarios where you expect a single result or none at all.

var customer = connection.QuerySingleOrDefault<Employee>("GetEmployeeById", parameters, commandType: CommandType.StoredProcedure);

In this example, we call the stored procedure named GetEmployeeById and pass the parameters we defined earlier. The result is mapped directly to an Employee object, which simplifies data handling in our application.

Mapping Results to an Object

Dapper excels at mapping database results to C# objects, reducing the amount of boilerplate code required for data access. When executing a stored procedure, Dapper automatically maps the result set to the specified type based on the property names.

public ActionResult Index() {
    using (var connection = new SqlConnection(connectionString)) {
        DynamicParameters parameters = new DynamicParameters();
        parameters.Add("id", 1);
        var customer = connection.QuerySingleOrDefault<Employee>("GetEmployeeById", parameters, commandType: CommandType.StoredProcedure);
        return View(customer);
    }
}

This complete method demonstrates how to set up the connection, define parameters, execute the stored procedure, and return the result to the view. The View(customer) call passes the Employee object to the view for rendering.

Procedure Used for Demo

Here is the SQL code for the stored procedure we are using in our example:

CREATE PROCEDURE GetEmployeeById
    @Id INT
AS
BEGIN
    SELECT * FROM Employees WHERE Id = @Id;
END

Edge Cases & Gotchas

When using stored procedures with Dapper, there are several edge cases and potential pitfalls to be aware of:

  • Null Parameters: If a parameter is optional and not provided, ensure your stored procedure can handle null values appropriately to avoid runtime errors.
  • Type Mismatch: Ensure that the types of parameters in your C# code match those defined in the stored procedure. A mismatch can lead to exceptions or incorrect results.
  • Result Set Mismatch: If the structure of the result set returned by the stored procedure does not match the properties of the mapped object, Dapper may not populate the object correctly. Always verify the mapping.
  • Transaction Management: If your stored procedures involve multiple operations that need to be atomic, consider wrapping calls in a transaction.

Performance & Best Practices

To maximize performance and maintainability when using Dapper with stored procedures, consider the following best practices:

  • Use Stored Procedures for Complex Logic: Encapsulate complex business logic in stored procedures to reduce the amount of SQL code in your application and improve maintainability.
  • Parameterize Queries: Always use parameters to avoid SQL injection attacks. Dapper's DynamicParameters makes this easy.
  • Limit Result Sets: When designing stored procedures, limit the amount of data returned by using SELECT statements effectively to improve performance.
  • Monitor Execution Plans: Regularly review execution plans for your stored procedures to identify performance bottlenecks and optimize queries as necessary.
  • Use Asynchronous Calls: If your application requires high scalability, consider using asynchronous methods provided by Dapper to improve responsiveness.

Conclusion

By leveraging Dapper's capabilities, we've learned how to use stored procedures with parameters to interact with databases efficiently. This approach enhances code organization, improves security by preventing SQL injection, and allows for seamless integration of database operations in .NET applications.

In summary, here are the key takeaways:

  • Stored procedures encapsulate business logic and improve performance.
  • Dapper simplifies database access and mapping results to objects.
  • DynamicParameters allows for flexible parameter passing.
  • Understanding edge cases can prevent runtime errors.
  • Implementing best practices ensures maintainable and efficient code.

Incorporating stored procedures with Dapper not only streamlines database access but also contributes to a cleaner and more maintainable codebase. This knowledge is valuable for developers aiming to build robust and scalable applications in the .NET ecosystem.

S
Shubham Batra
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Dapper vs Entity Framework in ASP.NET Core: Choosing the Right Data Access Strategy
Apr 12, 2026
Performance Tuning NHibernate for ASP.NET Core Applications
Apr 05, 2026
Mastering Async and Await in C#: A Comprehensive Guide
Mar 16, 2026
Get random number in asp.net C#
Dec 23, 2023
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    HTTP Error 500.32 Failed to load ASP NET Core runtime 6,925 views
  • 2
    Error-An error occurred while processing your request in .… 11,259 views
  • 3
    Comprehensive Guide to Error Handling in Express.js 216 views
  • 4
    ConfigurationBuilder does not contain a definition for Set… 19,449 views
  • 5
    Mastering Unconditional Statements in C: A Complete Guide … 21,488 views
  • 6
    Mastering JavaScript Error Handling with Try, Catch, and F… 147 views
  • 7
    Unable to connect to any of the specified MySQL hosts 6,217 views

On this page

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1760
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor