如何使用Multi-Mapper创建多个一对多对象层次结构

时间:2012-12-12 09:03:30

标签: c# linq dapper

我有以下两个模型

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来获取数据并放入对象中。代码是belolw

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查询完成吗?或者我应该使用一些差异技术?

1 个答案:

答案 0 :(得分:3)

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