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?
- 有更聰明的方式來填充嵌套集合嗎?我雖然起初是關於字典,但也許有一個更簡單/更清晰的模式。
- 更多關卡嵌套怎麼樣?