-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInMemoryAccessors.cs
More file actions
56 lines (50 loc) · 1.97 KB
/
Copy pathInMemoryAccessors.cs
File metadata and controls
56 lines (50 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
namespace PepperX.QueryForge.InMemory;
/// <summary>
/// Ready-made value accessors for sources whose columns are not plain properties.
/// </summary>
/// <remarks>
/// The default accessor reads properties by name, which covers ordinary POCOs. These cover the other
/// common shapes without needing a wrapper type.
/// </remarks>
public static class InMemoryAccessors
{
/// <summary>
/// Reads columns out of a dictionary row, case-insensitively.
/// </summary>
/// <example>
/// <code>
/// var result = rows.ToQueryResult(query, InMemoryAccessors.ForDictionary());
/// </code>
/// </example>
public static Func<TRow, string, object?> ForDictionary<TRow>()
where TRow : IReadOnlyDictionary<string, object?>
=> static (row, column) =>
{
if (row is null)
return null;
foreach (var (key, value) in row)
{
if (string.Equals(key, column, StringComparison.OrdinalIgnoreCase))
return value is DBNull ? null : value;
}
return null;
};
/// <summary>
/// Maps caller-facing column names onto different property names before reading.
/// </summary>
/// <param name="columnToProperty">
/// Column name to property name. Names absent from the map are read as-is.
/// </param>
/// <remarks>
/// Useful when the names a client sends are part of your API contract and should not be forced
/// to track how the model happens to be written.
/// </remarks>
public static Func<TModel, string, object?> WithColumnMap<TModel>(
IReadOnlyDictionary<string, string> columnToProperty)
{
ArgumentNullException.ThrowIfNull(columnToProperty);
var map = new Dictionary<string, string>(columnToProperty, StringComparer.OrdinalIgnoreCase);
var inner = Querying.PropertyAccessor.For<TModel>();
return (row, column) => inner(row, map.GetValueOrDefault(column, column));
}
}