2012-12-12 50 views
2

我有我的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; } 
} 

我用短小精悍来获取数据并投入对象。代码如下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,フニツ等。对于所有外键是RecordId它自己。

可以通过这个LINQ查询做什么?或者我应该使用一些差异技术?

回答

3

小巧玲珑不包括内置的重建从不同组的父/子关系的东西。

你或许可以概括的情况是这样的:

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

但我的所有孩子的不是相同的结构。我会更新我的问题 –

+0

请检查更新questrion。 FSubsystem&FReferences是diff结构。 –

+0

你可以看一下马新问题http://bit.ly/UnUNg1 –