How do you call a stored procedure with Dapper?

May 15, 2020

During one of my latest renditions of Better Object Relational Mapping with Dapper, the question arose about using stored procedures.

How do you call a stored procedure with Dapper?

using (var connection = new SqlConnection(CONNECTION_STRING))
{
    var storedProcedureName = "getAllUsers";

    var results = await connection
        .QueryAsync<ApplicationUser>(storedProcedureName, 
                                commandType: CommandType.StoredProcedure);
}

Looking at the code above, calling a stored procedure is similar to calling any other query with Dapper.

Free ebook: 10 Tricks to Supercharge Your ASP.NET Core Applications

I'm hard at work on a new FREE ebook to help you supercharge your ASP.NET Core applications. Join the list today, and I'll send you the chapters as they're done!

But what if your Stored Procedure doesn't return a result? No problem. ExecuteAsync works just as well.

using (var connection = new SqlConnection(CONNECTION_STRING))
{
    var storedProcedureName = "deleteAllUsers";

    await connection.ExecuteAsync(storedProcedureName, 
                            commandType: CommandType.StoredProcedure);
}

And there you go! Using stored procedures with Dapper can be a great way to take advantage of the strengths of the database while reducing complexity of your code.