Table of Contents

Shaping rows

Map<T>() reads each row into a T: one column feeds one member, by name. Most of the time that is all you need, and Mapping rows to objects says how it works. This page is for the other times: the row you want is not quite the row the query returns.

Every shape below has a recipe, and none of them needs a new API. Where the library has no feature for something, the page says so and says what to write instead. Every example is compiled and run against an in-memory SQLite database.

You want Write
A NULL to become an empty string [NullValue("")], or [NullPolicy(NullAction.Default)] and the member's initializer, or a factory map
A value that is not in the row Set it after the close, or return it from the query
A column to be left alone A pair with a null column
A mapping that fails when a column is missing A required member (not with a factory map)
A mapping that reads only what you list A factory map
A converter inside the collection syntax Not available: Convert on the map
A row with more than 16 values A constructor, or a factory: no limit
Only some of the rows The query's WHERE, else filter after the close
One column, by name Select only that column and use Map<long?>()

What a factory map is

A constructor makes a T from the columns of a row, matching each parameter to a column by name. A factory map does the same with a function you write: RowMap<T>.From(factory) takes a delegate, usually a lambda, and calls it once per row. Use one when the type should not carry a column-shaped constructor, when it is not yours, or when it has several constructors.

  • The parameters are matched to columns by name, with the three tiers a constructor parameter uses: exactly, ignoring case, then ignoring case and underscores. tag_name feeds tagName. A pair renames one, and in a factory map the pair's key is the name of the parameter.
  • It maps only its parameters. No member of the T is set from a column afterwards. What the function does not take, the map does not read.
  • A NULL and a missing column follow the constructor rule. A parameter no column feeds gets its declared default value, else default. A NULL into a nullable parameter (string?, int?) is null, and into a non-nullable one throws ValueMappingException naming the model and the row, unless the model type's null policy says otherwise. A function that must see a NULL declares the parameter nullable.
  • Declare it once. A map builds its row reader on first use and keeps it, so it belongs in a static property, not in the call.
  • It is checked when From runs, not by the compiler: a function that returns another type, a pair that names no parameter, and a single value as the T (RowMap<long>.From(...)) each throw there. For a map held in a property, that is the first use of the property.

NULLs that mean an empty string

You may look for a WhenNull(member, ""), or for a string? converter that is called for NULL, so that Label gets "" when the column is NULL. Neither exists: the member's declaration is where its NULL value lives. Write the value in its initializer and declare [NullPolicy(NullAction.Default)] (or [NullValue("")] on the member); a converter is not called for the NULL:

[NullPolicy(NullAction.Default)]
public class Tag
{
    public int Id { get; init; }
    public string Label { get; init; } = "";
    public string Description { get; init; } = "";
}
// Tag is NullAction.Default: a NULL keeps the initializer,
// and the converter is not called for it:
// Label keeps "" and Description keeps its own.
// The member's declaration is where its NULL value lives.
public static RowMap<Tag> TagMap
    => field ??= RowMap<Tag>
        .From([new(nameof(Tag.Label), "tag_name")])
        .Convert<string, string>(
            nameof(Tag.Label),
            static label
                => label.Trim());

With a row whose tag_name is NULL, Label is "". With ' NEWS ' it is "NEWS". The model needs nullable annotations on (<Nullable>enable</Nullable>), as the NULL rules say.

The other recipe is a factory map. The function receives null for a NULL in a parameter declared string?, and decides what it means:

// A factory parameter declared string? receives null for a NULL,
// so the function can decide what NULL means.
// The pairs are not needed: tag_name matches tagName.
public static RowMap<Tag> TagFactoryMap
    => field ??= RowMap<Tag>.From(
        static (int id, string? tagName, string? description)
            => new Tag
            {
                Id = id,
                Label = tagName?.Trim() ?? "",
                Description = description ?? "",
            });
Tag[] fromInitializer = await connection
    .Command("select id, tag_name, description from tags order by id")
    .Map(ShapingMaps.TagMap)
    .ToArrayAsync(cancellationToken);

Tag[] fromFactory = await connection
    .Command("select id, tag_name, description from tags order by id")
    .Map(ShapingMaps.TagFactoryMap)
    .ToArrayAsync(cancellationToken);

A converter that must see a NULL asks for a nullable value type as its column type (DateTime?): see Converting a column. A nullable string? says nothing at run time, so a converter over text is never called for NULL.

A value that is not in the row

You may look for a .With(nameof(Post.Serial), value) that puts a value from outside the query into every row. There is no such method. Two recipes cover it.

When the member is settable, set it after the close. The reader is closed when the terminal returns, so the rows are yours:

public class PostStamp
{
    public int Id { get; init; }
    public string Title { get; init; } = "";
    public string Serial { get; set; } = "";
}
// The reader is closed when ToArrayAsync returns,
// so the rows are yours to change.
PostStamp[] stamps = await connection
    .Command("select id, title from posts order by id")
    .Map<PostStamp>()
    .ToArrayAsync(cancellationToken);

foreach (PostStamp stamp in stamps)
    stamp.Serial = serial;

When the member is init-only, or the type is a record, let the query return the value as a column (in a stored procedure, select @serial as serial beside the rest). The map fills it like any other member, and it needs no setter:

public class PostStampInit
{
    public int Id { get; init; }
    public string Title { get; init; } = "";
    public string Serial { get; init; } = "";
}
// Or let the query return it as a column:
// the map then fills Serial like any other member,
// even when it is init-only.
PostStampInit[] fromQuery = await connection
    .Command("select id, title, @serial as serial from posts order by id")
    .AddParam("serial", serial)
    .Map<PostStampInit>()
    .ToArrayAsync(cancellationToken);

Leaving a column alone

You may look for an Ignore(member). It exists as a pair whose column is the C# null (not SQL NULL): the member is not read, even if the result has a column of its name.

public class Author
{
    public string Handle { get; init; } = "";
    public string City { get; init; } = "";
    public string Editor { get; init; } = "";
}
// A null column means "do not map this member":
// City keeps its initializer,
// even though the result has a city column.
public static RowMap<Author> NoCityMap
    => field ??= [
        new(nameof(Author.City), null),
    ];
Author[] ignored = await connection
    .Command("select handle, city, editor from authors order by handle")
    .Map(ShapingMaps.NoCityMap)
    .ToArrayAsync(cancellationToken);

City is "" in every row although the query returns city. The null needs no ! after it.

Being strict

There is no strict mode, because a mode would change every rule. There are three ways to say what you mean, each at the place it applies:

  • A member that must have a column is required. When the columns of a result include none for it, the first row throws ValueMappingException, and an empty result never reports it, because no row is read. The routes that know the columns before the first row report it before any row: see required and init members. This holds for Map<T>() without a factory.
  • A member that must never be filled is a pair with a null column, as above, on a member that is not required (a null column for a required member throws ArgumentException when the map is created).
  • A map that reads only what it lists is a factory map. Its function takes the columns it names and no member is filled by name afterwards.
public class StrictAuthor
{
    public required string Handle { get; init; }
    public string Editor { get; init; } = "";
}
ValueMappingException? missing = null;
try
{
    // No column feeds Handle, so the first row throws.
    _ = await connection
        .Command("select editor from authors order by handle")
        .Map<StrictAuthor>()
        .ToArrayAsync(cancellationToken);
}
catch (ValueMappingException ex)
{
    missing = ex;
}
// A factory map fills only what its function takes:
// no member is set from a column afterwards.
// A parameter with no column gets its declared default, else default,
// and nothing throws.
public static RowMap<Author> ListedOnlyMap
    => field ??= RowMap<Author>.From(
        static (string handle, string? editor)
            => new Author
            {
                Handle = handle,
                Editor = editor ?? "unknown",
            });

A factory map does not fail on a missing column. A parameter no column feeds follows the constructor rule, so it gets its default:

// No column feeds editor: it is null, so the function says "unknown".
// The factory did not throw.
Author[] noEditorColumn = await connection
    .Command("select handle from authors order by handle")
    .Map(ShapingMaps.ListedOnlyMap)
    .ToArrayAsync(cancellationToken);

A converter in the collection

You may look for the converter inside the collection syntax, as [new("Label", "tag_name", static label => label.Trim())]. That form is not available. Write a map, then call Convert<TColumn, TMember>(member, function) on it, as in the first recipe above.

More than 16 parameters

The Func delegates of C# stop at 16 parameters, so a lambda with more looks like a limit. There is none. A record or a class with a constructor of 17 parameters is built by Map<T>() like any other:

public record WideReading(
    int Channel01,
    int Channel02,
    int Channel03,
    int Channel04,
    int Channel05,
    int Channel06,
    int Channel07,
    int Channel08,
    int Channel09,
    int Channel10,
    int Channel11,
    int Channel12,
    int Channel13,
    int Channel14,
    int Channel15,
    int Channel16,
    int Channel17);
// The query selects channel01 to channel17.
// The record's constructor takes all 17: no factory is needed.
WideReading reading = await connection
    .Command(sql)
    .Map<WideReading>()
    .SingleAsync(cancellationToken);

A factory takes more than 16 parameters too.

Rows you do not want

You may look for a way to skip a row before it is built: a predicate over the raw columns, or a factory that may return nothing. The library has no such feature. These are the places for the filter, best first.

In the query. The WHERE is the place for it: the database skips the rows, nothing is read or built for them. A column that only decides whether a row is kept belongs in the WHERE, not in the select list.

    // Recommended: filter in the query's WHERE.
    // The database skips the rows, so they never reach the reader.
Post[] inSql = await connection
    .Command("select id, title from posts where views > @views order by id")
    .AddParam("views", 20)
    .Map<Post>()
    .ToArrayAsync(cancellationToken);

After the close. When the decision needs your code, read the rows, let the reader close, then filter the array.

// When the decision needs code, read the rows and filter the array:
// the reader is closed by then.
Post[] all = await connection
    .Command("select id, title from posts order by id")
    .Map<Post>()
    .ToArrayAsync(cancellationToken);

Post[] afterClose = [.. all.Where(static post => post.Id > 2)];

A factory that returns null. It is the way to read a value only to decide, because the parameter that holds it is not kept in the object. The skipped rows are null entries in the result until you drop them.

// A factory may return null: the row is then a null in the result.
// views rides along only to make the decision,
// and no member holds it.
public static RowMap<Post> BusyPostMap
    => field ??= RowMap<Post>.From(
        static (int id, string title, int views)
            => views > 20
                ? new Post { Id = id, Title = title }
                : null);
// The nulls the factory returned are in the list until you drop them.
List<Post> withNulls = await connection
    .Command("select id, title, views from posts order by id")
    .Map(ShapingMaps.BusyPostMap)
    .ToListAsync(cancellationToken);

Post[] busy = [.. withNulls.Where(static post => post is not null)];

One column, by name

You may look for Map<long?>("last_id"). There is no name to give: Map<long?>() reads the first column of each row as one value, whatever its name, and long? gives null for a NULL. Select only the column you want:

// Select only the column you want:
// Map<long?>() reads the first column of each row as one value.
// max() over no rows is NULL, which is null here.
long? none = await connection
    .Command("select max(id) from posts where author = @author")
    .AddParam("author", 99)
    .Map<long?>()
    .FirstOrDefaultAsync(cancellationToken);

long? some = await connection
    .Command("select max(id) from posts where author = @author")
    .AddParam("author", 42)
    .Map<long?>()
    .FirstOrDefaultAsync(cancellationToken);

A factory map is not the way for one value: RowMap<long>.From(...) is rejected, because a single value is not a row model. To read a column that is not the first of several, write the read yourself with Map(selector).