我有我的 2 个模型,如下所示
public class FItem
{
public FItem() { }
public int RecordId { get; set; }
public int MarketId { get; set; }
public string ItemName { get; set; }
public string ItemFamily { get; set; }
public string HoverFamily { get; set; }
public string ItemDesc { get; set; }
public IEnumerable<FSubsystem> FSubsystems { get; set; }
}
public class FSubsystem
{
public FSubsystem() { }
public int FSubsystemId { get; set; }
public int RecordId { get; set; } //Foreign key
public int supplierId { get; set; }
public int SubSystemTypeId { get; set; }
public double Percentage { get; set; }
public double? Value { get; set; }
}
public class FReferences
{
public FReferences() { }
public int RecordID { get; set; } //Foreign key
public int SourceID { get; set; }
public DateTime SourceDate { get; set; }
public string Reference { get; set; }
public int? ReferenceID { get; set; }
}
我使用 dapper 来获取数据并放入对象中. 代码就像贝洛尔一样
using (var multi = mapperConnection.QueryMultiple("USP_FetchMarketRecords", parameters, (SqlTransaction)null, 1000000, CommandType.StoredProcedure))
{
IEnumerable<MarketRecord.FItem> FItem = multi.Read<MarketRecord.FItem>().ToList();
IEnumerable<MarketRecord.FSubsystem> FSubsystem = multi.Read<MarketRecord.FSubsystem>().ToList();
}
现在我想获取每个记录 ID 的子系统,并将它们放在 Fitem 的 FSubsystems 属性中。我该怎么做?
在这里,我只显示与 FItem 的一对多关系,即 Fsubsystem 。但是我有很多一对多表要Fitem,例如FReferenc,FUnit等。对于所有外键都是 RecordId itelf。
这可以通过linq查询来完成吗?或者我应该使用一些差异技术吗?
Dapper 不包含任何内置的内容来重建来自不同集合的父/子关系。
您可能可以概括为这样的场景:
static void ApplyParentChild<TParent, TChild, TId>(
this IEnumerable<TParent> parents, IEnumerable<TChild> children,
Func<TParent, TId> id, Func<TChild, TId> parentId,
Action<TParent, TChild> action)
{
var lookup = parents.ToDictionary(id);
foreach (var child in children)
{
TParent parent;
if (lookup.TryGetValue(parentId(child), out parent))
action(parent, child);
}
}
因此,如果我们有:
List<Parent> parents = new List<Parent> {
new Parent { Id = 1 },
new Parent { Id = 2 }
};
List<Child> children = new List<Child> {
new Child { Id = 3, ParentId = 1},
new Child { Id = 4, ParentId = 2},
new Child { Id = 5, ParentId = 1}
};
您可以使用:
parents.ApplyParentChild(children, p => p.Id, c => c.ParentId,
(p,c) => p.Children.Add(c));