讓我們說我有一系列形成聚合的對象。
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具有一對多關係。
因此,對於給定的AI ID,我希望我的對像也擁有所有子數據。
我最好的猜測是我應該以某種方式使用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級層次結構。