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#
var count = await db.ScalarAsync<int>("dbo.usp_User_Count");
Nullable example#
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#
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
GuidDateOnlyTimeOnly
For example, an integer-based status column can be read as an enum value directly.
Notes#
- scalar reads return
defaultwhen there are no rows - scalar reads return
defaultwhen the first value isDBNull - strict auto mapping does not affect scalar operations