我该如何有效地选择用精致小巧的聚合对象? [英] How do I select an aggregate object efficiently using Dapper?

查看:173
本文介绍了我该如何有效地选择用精致小巧的聚合对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一系列形成一个聚合对象。

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 {get;set;}
  public List<C> Items {get;set;}
}

public class A{
  public long ID {get;set;}
  public string Details {get;set;}
  public List<B> Items {get;set;}
}

使用短小精悍,什么是从数据库中的表填充这些的最好方法(在我的情况下,它的Postgres但是这不应该的问题)。在实施例中的表是pretty多一个对一个与对象模型。到各个下属对象的类重presenting外键关系的项目属性。即3桌,有一个上有B多关系,B有一个用C一对多的关系。

using Dapper, what is the best way to populate these from tables in a database (in my case it's postgres but that shouldn't matter). The tables in the example are pretty much one for one with the object model. The Items property on the class representing foreign key relationships to each subordinate object. i.e. 3 tables, A has a One to Many relationship with B, B has a One to Many relationship with C.

所以对于我想要一个给定的ID我的对象有他们的所有子数据以及

So for a given ID of A I want my objects to have all their child data as well.

我最好的猜测是,我应该以某种方式使用QueryMultiple,但我不知道如何最好地做到这一点。

My best guess is that I should use QueryMultiple somehow but I am not sure how best to do it.

推荐答案

我想我在这里提出的助手:<一href=\"http://stackoverflow.com/questions/6379155/help-with-multi-mapper-to-create-object-hierarchy/6380756#6380756\">Help与多映射创建可能有帮助对象层次。

I think the helper I propose here: Help with 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};  
    );

假设您延长GridReader和一个映射:

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

您可以扩展这种模式有一个3级层次结构的工作。

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

这篇关于我该如何有效地选择用精致小巧的聚合对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆