Docs / Read Scalar Values

Read Scalar Values

What this page covers#

This page explains how to read scalar values with MooDb and what conversion support is provided.

What is a scalar value#

A scalar value is a single value taken from the first column of the first row.

Common examples are:

  • a count
  • an ID
  • a status value
  • a date or timestamp

Basic example#

</> C#
var count = await db.ScalarAsync<int>("dbo.usp_User_Count");

Nullable example#

</> C#
int? count = await db.ScalarAsync<int?>("dbo.usp_User_Count");

Use a nullable type when absence must be distinct from a non-null default value.

Raw SQL example#

</> C#
var count = await db.Sql.ScalarAsync<int>(
    "SELECT COUNT(*) FROM [dbo].[tbl_User];");

Conversion support#

Scalar conversion uses the same central conversion pipeline used by mapping.

That means conversions such as the following are supported:

  • enums from integer values
  • enums from string values when the text matches the enum name
  • nullable enums
  • Guid
  • DateOnly
  • TimeOnly

For example, an integer-based status column can be read as an enum value directly.

Notes#

  • scalar reads return default when there are no rows
  • scalar reads return default when the first value is DBNull
  • strict auto mapping does not affect scalar operations