Docs / Your First Stored Procedure Call

Your First Stored Procedure Call

What this page covers#

This page shows the normal MooDb path: calling a stored procedure.

Why this is the default path#

MooDb is stored procedure first.

That means the main MooDb methods are designed around stored procedure names. If you need raw SQL text, that lives on db.Sql instead.

The simple version#

The normal shape looks like this:

</> C#
var result = await db.SomeMethodAsync(
    "dbo.usp_Something",
    parameters);

First example: read one row#

</> C#
public sealed class User
{
    public int UserId { get; set; }
    public string Email { get; set; } = string.Empty;
    public string DisplayName { get; set; } = string.Empty;
}

var user = await db.SingleAsync<User>(
    "dbo.usp_User_GetById",
    new MooParams().AddInt("@UserId", 1));

How it works#

  • "dbo.usp_User_GetById" is the stored procedure name
  • MooParams builds the SQL Server parameters
  • SingleAsync<User> expects zero or one row
  • if zero rows come back, the result is null
  • if more than one row comes back, MooDb throws

Another example: read many rows#

</> C#
var users = await db.ListAsync<User>(
    "dbo.usp_User_List");

Another example: execute a non-query command#

</> C#
var rowsAffected = await db.ExecuteAsync(
    "dbo.usp_User_UpdateDisplayName",
    new MooParams()
        .AddInt("@UserId", 1)
        .AddNVarChar("@DisplayName", "Ada Lovelace", 200));

Why MooDb is shaped this way#

MooDb uses the main MooDbContext surface for stored procedures because it wants the default path to be obvious and consistent.

Raw SQL still exists, but it lives on db.Sql.