Path: redb-route/redb.Route.Sql/Mapping/PocoRowMapper.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Mapping/PocoRowMapper.cs
----
using System.Collections.Concurrent;
using System.Data.Common;
using System.Reflection;
namespace redb.Route.Sql.Mapping;
///
/// Maps a row to a POCO of type
/// via reflection. Caches property accessors per type for performance.
/// Supports case-insensitive and snake_case → PascalCase column matching.
///
///
/// A column without a writable property is skipped. A value reaches its property only when the conversion is lossless and
/// unambiguous (see ); a NULL sets a nullable or reference property to null. Anything else —
/// a NULL for a value type, an overflow, a timestamp without a time zone for a — throws, as
/// Apache Camel's BeanPropertyRowMapper refuses a type mismatch.
///
/// POCO type with a parameterless constructor.
public sealed class PocoRowMapper : ISqlRowMapper where T : new()
{
private static readonly ConcurrentDictionary _propertyCache = new(StringComparer.OrdinalIgnoreCase);
private static readonly PropertyInfo[] _allProps = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
///
///
/// A column's value cannot be assigned to its property without loss or guessing. The message names the column, the
/// property and both types, never the value.
///
public T Map(DbDataReader reader)
{
var obj = new T();
var fieldCount = reader.FieldCount;
for (var i = 0; i < fieldCount; i++)
{
var columnName = reader.GetName(i);
var prop = ResolveProperty(columnName);
if (prop == null || !prop.CanWrite) continue;
if (reader.IsDBNull(i))
{
if (!SqlValueConverter.AcceptsNull(prop.PropertyType))
throw MappingError(columnName, "NULL", prop, "a NULL cannot be assigned to a non-nullable value type; make the property nullable");
prop.SetValue(obj, null);
continue;
}
var value = reader.GetValue(i);
if (!SqlValueConverter.TryConvert(value, prop.PropertyType, out var converted, out var reason))
throw MappingError(columnName, value.GetType().Name, prop, reason);
prop.SetValue(obj, converted);
}
return obj;
}
private static SqlRowMappingException MappingError(string column, string sourceType, PropertyInfo prop, string reason) =>
new($"Column '{column}' ({sourceType}) cannot be assigned to {typeof(T).Name}.{prop.Name} " +
$"({SqlValueConverter.TypeName(prop.PropertyType)}): {reason}.");
private static PropertyInfo? ResolveProperty(string columnName) =>
_propertyCache.GetOrAdd(columnName, name => ColumnNameMatcher.Find(_allProps, name));
}