Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper multi-mapping Async extension

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

like image 648
Ajt Avatar asked Jan 09 '17 06:01

Ajt


1 Answers

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;
}
like image 164
David Pine Avatar answered Oct 13 '22 08:10

David Pine