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.

Live stream notifications? New posts? Thought-provoking conversations? Sign up today!

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.