2012-12-12 51 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 –