Inline Mappers - lobodava/artisan-orm GitHub Wiki

All ReadTo* methods accept a Func<SqlDataReader, T> parameter, so besides registered [MapperFor] mappers and reflection-based auto-mapping, you can pass a one-off lambda inline.

This is useful for:

  • Anonymous-typed projections — types you don't want to declare globally.
  • Tuples — when you need just two or three columns and don't want a class.
  • Existing classes you can't / don't want to decorate with [MapperFor].

Anonymous-typed projection

var summary = cmd.ReadTo(dr => new
{
    Id    = dr.GetInt32(0),
    Login = dr.GetString(1),
});

Tuple

var (id, name) = cmd.ReadTo(dr => (dr.GetInt32(0), dr.GetString(1)));

One-off class

var user = cmd.ReadTo(dr => new User
{
    Id    = dr.GetInt32  (0),
    Login = dr.GetString (1),
    Name  = dr.GetString (2),
    Email = dr.GetString (3),
});

The same pattern works for list-returning methods:

IList<(int Id, string Code)> roles = cmd.ReadToList(dr =>
    (Id: dr.GetByte(0), Code: dr.GetString(1)));

When to switch to a registered [MapperFor]

If the same shape is read in more than one or two places, move it to a registered mapper — single source of truth, plus the option to also produce ObjectRow and DataTable forms (for table-valued parameters and bulk save).

Performance

Inline mappers compile to a normal C# delegate at the call site — there is no reflection, no expression-tree machinery, and no caching, so they are as fast as hand-written [MapperFor] ones. The only "cost" is that they live with the call, not with the type.


See also: