Skip to the content.

The QueryFirstOrDefault<T>(...) and QuerySingleOrDefault<T>(...) APIs return default(T) if zero rows are returned.

For reference-type T, you can then use a null test to see whether a row came back, but a value-type T (that isn’t Nullable<T>, aka T?) is never null, so it will be hard to test whether a row came back.

This does not impact QueryFirst<T>(...) or QuerySingle<T>(...) because they throw if zero rows are returned - you do not need to test anything.

As a fix, consider using Nullable<T> for such scenarios:

Bad:

var row = conn.QueryFirstOrDefault<YourStruct>(sql);
if (row is not null)
{
    // ...
}

Good:

var row = conn.QueryFirstOrDefault<YourStruct?>(sql);
if (row is not null)
{
    // ...
}