Below is my extension for multi mapping (one to many relationship) in dapper
public static IEnumerable<TParent> QueryParentChild<TParent, TChild, TParentKey>(
this IDbConnection connection,
string sql,
Func<TParent, TParentKey> parentKeySelector,
Func<TParent, IList<TChild>> childSelector,
dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int? commandTimeout = null, CommandType? commandType = null)
{
Dictionary<TParentKey, TParent> cache = new Dictionary<TParentKey, TParent>();
connection.Query<TParent, TChild, TParent>(
sql,
(parent, child) =>
{
if (!cache.ContainsKey(parentKeySelector(parent)))
{
cache.Add(parentKeySelector(parent), parent);
}
TParent cachedParent = cache[parentKeySelector(parent)];
IList<TChild> children = childSelector(cachedParent);
children.Add(child);
return cachedParent;
},
param as object, transaction, buffered, splitOn, commandTimeout, commandType);
return cache.Values;
}
Now i want to convert this to async method. i have tried many ways.But got some errors..Pls let me know the changes need to be done
Did you try something like this, see below:
public static async Task<IEnumerable<TParent>> QueryParentChildAsync<TParent,
TChild,
TParentKey>(
this IDbConnection connection,
string sql,
Func<TParent, TParentKey> parentKeySelector,
Func<TParent, IList<TChild>> childSelector,
dynamic param = null,
IDbTransaction transaction = null,
bool buffered = true,
string splitOn = "Id",
int? commandTimeout = null,
CommandType? commandType = null)
{
var cache = new Dictionary<TParentKey, TParent>();
await connection.QueryAsync<TParent, TChild, TParent>(
sql,
(parent, child) =>
{
var key = parentKeySelector(parent);
if (!cache.ContainsKey(key ))
{
cache.Add(key, parent);
}
var cachedParent = cache[key];
var children = childSelector(cachedParent);
children.Add(child);
return cachedParent;
},
param as object,
transaction,
buffered,
splitOn,
commandTimeout,
commandType);
return cache.Values;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With