How do I select an aggregate object efficiently using Dapper?

前端 未结 1 1553
忘掉有多难
忘掉有多难 2020-12-04 13:52

Lets say that I have a series of objects that form an aggregate.

public class C{
 public string Details {get;set;}
}

public class B{
  public string Details         


        
相关标签:
1条回答
  • 2020-12-04 14:23

    I think the helper I propose here: Multi-Mapper to create object hierarchy may be of help.

    var mapped = cnn.QueryMultiple(sql)
       .Map<A,B,A>
        (
           A => A.ID, 
           B => B.AID,
           a, bees => { A.Items = bees};  
        );
    

    Assuming you extend your GridReader and with a mapper:

    public static IEnumerable<TFirst> Map<TFirst, TSecond, TKey>
        (
        this GridReader reader,
        Func<TFirst, TKey> firstKey, 
        Func<TSecond, TKey> secondKey, 
        Action<TFirst, IEnumerable<TSecond>> addChildren
        )
    {
        var first = reader.Read<TFirst>().ToList();
        var childMap = reader
            .Read<TSecond>()
            .GroupBy(s => secondKey(s))
            .ToDictionary(g => g.Key, g => g.AsEnumerable());
    
        foreach (var item in first)
        {
            IEnumerable<TSecond> children;
            if(childMap.TryGetValue(firstKey(item), out children))
            {
                addChildren(item,children);
            }
        }
    
        return first;
    }
    

    You could extend this pattern to work with a 3 level hierarchy.

    0 讨论(0)
提交回复
热议问题