English 中文(简体)
如何使用Dapper有效地选择聚合对象?
原标题:How do I select an aggregate object efficiently using Dapper?
  • 时间:2011-05-27 01:30:38
  •  标签:
  • c#
  • sql
  • dapper

假设我有一系列的对象,它们形成了一个集合。

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

使用Dapper,从数据库中的表中填充这些数据的最佳方式是什么(在我的情况下是postgres,但这无关紧要)。示例中的表与对象模型几乎是一一对应的。类上的Items属性表示与每个从属对象的外键关系。即3个表,A与B具有一对多关系,B与C具有一对很多关系。

因此,对于给定的ID a,我希望我的对象也有它们的所有子数据。

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

最佳回答

我认为我在这里建议的帮助者:创建对象层次结构的Multi-Mapper可能会有所帮助。

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

假设您扩展了GridReader并使用映射程序:

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级层次结构。

问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签