How do you call a stored procedure with Dapper?

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.

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.

Kevin Griffin - Microsoft MVP and .NET Expert

About Kevin

Kevin Griffin has been running production .NET applications and teaching developers for over two decades. A 16-time Microsoft MVP specializing in ASP.NET Core and Azure, Kevin brings real-world experience from his own SaaS products alongside his consulting work at Swift Kick. He's hosted the Hampton Roads .NET User Group since 2009 and founded RevolutionVA, the nonprofit behind Hampton Roads DevFest. Kevin's talks blend hard-won lessons from production systems with practical advice you can use Monday morning.

Categories

Tags