Dapper Asynchronous Multiplexing Extension

Below is my extension for multiple display (one to many) 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 an async method. I have tried many ways. But got some errors. Pls tell me that changes need to be made.

+5
source share
1 answer

You tried something like this, see below:

 public static async 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; } 
+1
source

Source: https://habr.com/ru/post/1262511/


All Articles