2016-04-25 74 views
1
嵌套集合

想象我有一個存儲過程應返回三個表:填充的DataReader

SELECT AID, AName 
FROM AThings 

SELECT BID, BName, AID 
FROM BThings 

SELECT CID, CName, BID 
FROM CThings 

在一個類表示:

public class AThing 
{ 
    int AID { get; set; } 
    string AName { get; set;} 
    Dictionary<int, BThing> BThingsColl { get; set;} 
} 

public class BThing 
{ 
    int BID { get; set; } 
    string BName { get; set;} 
    int AID { get; set; } 
    List<CThing> CThingsColl { get; set;} 
} 

public class CThing 
{ 
    int CID { get; set; } 
    string CName { get; set;} 
    int BID { get; set; } 
} 

CThing具有BThing參考,BThing具有參考到AThing

要執行的存儲過程,並填充我的目標,我使用的是DataReader

using (SqlDataReader dr = cmd.ExecuteReader()) 
{ 
    var results = new Dictionary<int, AThing>(); 

    while(dr.Read()) 
    { 
     var downloadedAThing = new AThing(); 
     downloadedAThing.BThingsColl = new Dictionary<int, BThing>(); 

     downloadedAThing.AID = dr.GetInt32(0); 
     downloadedAThing.AName = dr.GetString(1); 

     results.Add(downloadedAThing.AID, downloadedAThing); 
    } 

    if (dr.NextResult) 
    { 
     while(dr.Read()) 
     { 
      var downloadedBThing = new BThing(); 
      downloadedBThing.CThingsColl = new List<CThing>(); 

      downloadedBThing.BID = dr.GetInt32(0); 
      downloadedBThing.BName = dr.GetString(1); 
      downloadedBThing.AID = dr.GetInt32(2); 

      results[downloadedBThing.AID].BThingsColl.Add(downloadedBThing.BID, downloadedBThing); 
     } 
    } 

    if (dr.NextResult) 
    { 
     while(dr.Read()) 
     { 
      var downloadedCThing = new CThing(); 

      downloadedCThing.CID = dr.GetInt32(0); 
      downloadedCThing.CName = dr.GetString(1); 
      downloadedCThing.BID = dr.GetInt32(2); 

      int AThingID = // How to retreive me? 
      results[AThingID].BThingsColl[downloadedCThing.BID].Add(downloadedCThing); 
     } 
    } 
} 
  • 在第三排料,我怎麼能retreive的AThingID?
  • 有更聰明的方式來填充嵌套集合嗎?我雖然起初是關於字典,但也許有一個更簡單/更清晰的模式。
  • 更多關卡嵌套怎麼樣?

回答

1

與您現有的代碼保持一致,我認爲最簡單的方法是創建一個臨時的字典,然後創建後添加到它的BThing:

BIDtoAID.Add(downloadedBThing.BID, downloadedBThing.AID); 

Dictionary<int, int> BIDtoAID = new Dictionary<int, int>(); 

創建downloadedBThing後

然後,當創建CThing:

int AThingID = BIDtoAID[downloadedCThing.BID]; 

如果你正在處理很多記錄,我認爲用這些ID保留一個臨時字典將是最高性能的。