2017-01-09 15 views
5

Dưới đây là phần mở rộng của tôi cho nhiều bản đồ (một đến nhiều mối quan hệ) trong đoan trangDapper đa mapping Async mở rộng

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

Bây giờ tôi muốn chuyển đổi này để phương pháp async. tôi đã thử nhiều ways.But có một số errors..Pls cho tôi biết những thay đổi cần phải được thực hiện

Trả lời

1

Bạn có thử một cái gì đó như thế này, xem dưới đây:

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

Cảm ơn u rất nhiều @ David .. nó hoạt động ... tôi sẽ chấp nhận câu trả lời của bạn .. – Ljt