Dapper多映射异步扩展

时间:2017-01-09 06:58:12

标签: c# asp.net-core dapper

以下是我在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;
}

现在我想将其转换为异步方法。我尝试过很多方法。但是有些错误......请告诉我需要做的改变

1 个答案:

答案 0 :(得分:1)

你有没有尝试过这样的事情,见下文:

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;
}