Skip to content

Instantly share code, notes, and snippets.

@CarlosLanderas
Last active October 4, 2017 16:39
Show Gist options
  • Save CarlosLanderas/563699c40f115512b6015480f3a865e1 to your computer and use it in GitHub Desktop.
Save CarlosLanderas/563699c40f115512b6015480f3a865e1 to your computer and use it in GitHub Desktop.
Dapper Query Map Collections
public IEnumerable<T1> ReadWithMap<T1, T2, TReturn>(Func<T1, object> key, Func<T1, string> targetMap) where TReturn : T1
{
var lookup = new Dictionary<object, T1>();
var targetType = typeof(T1);
var propertyFlags = BindingFlags.Public | BindingFlags.Instance;
gridReader.Read<T1, T2, T1>((t1, t2) =>
{
if (!lookup.TryGetValue(key(t1), out T1 t1Return))
{
lookup.Add(key(t1), t1Return = t1);
}
MapTargetProperty(targetMap(t1Return), t2, t1Return);
return t1;
});
return lookup.Values;
}
private void MapTargetProperty(string propertyName, object source, object target)
{
if (source == null)
{
return;
}
var propertyFlags = BindingFlags.Public | BindingFlags.Instance;
var targetProperty = target.GetType().GetProperty(propertyName, propertyFlags);
var addMethod = targetProperty.PropertyType.GetMethod("Add");
addMethod.Invoke(targetProperty.GetValue(target, null), new object[] { source });
}
[Fact]
public async Task Test1()
{
var sqlQueries = @"
select A.Id, A.TypeId, A.PublishedAt, C.Id, C.Name, C.Surname, C.SecondSurname from Cards A
left join CardMentions B on A.Id = B.CardId
left join Users C on C.Id = B.UserId ";
var sqlConn = new SqlConnection("Server=.;Database=UriaDepartmentalSites;Trusted_Connection=True; MultipleActiveResultSets=True");
var database = new Database(sqlConn);
var reader = await database.QueryMultipleAsync(sqlQueries);
var result = reader.ReadWithMap<Card, User, Card>(c => c.Id, c => nameof(c.Users));
result.ElementAt(0).Users.Count().Should().Be(2);
result.ElementAt(5).Users.Count().Should().Be(3);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment