我們知道在T-SQL查詢中可以很方便地將兩個甚至是多個表的數據進行連接(join)操作,其結果就是新的結果集將包含多個表的列數據。
如果是在 客戶端的DataSet中,也希望實現這樣的效果,那麼需要怎麼做呢?
protected override void OnLoad(EventArgs e)
{
DataSet ds = PrepareDataSet();
gvCustomers.DataSource = ds.Tables[0];
gvOrders.DataSource = ds.Tables[1];
}
/// <summary>
/// 這個方法准備10個客戶,每個客戶有5個訂單
/// </summary>
/// <returns></returns>
private DataSet PrepareDataSet()
{
DataSet ds = new DataSet();
DataTable tb1 = new DataTable ("Customers");
tb1.Columns.AddRange(new[]
{
new DataColumn("CustomerID")
,new DataColumn("CompanyName")
});
DataTable tb2 = new DataTable ("Orders");
tb2.Columns.AddRange(new[]
{
new DataColumn("CustomerID")
,new DataColumn("OrderID",typeof(int))
,new DataColumn("OrderDate",typeof (DateTime))
});
ds.Tables.AddRange (new[] { tb1, tb2 });
//添加關系
ds.Relations.Add("Customers_Orders_Relation", tb1.Columns ["CustomerID"], tb2.Columns["CustomerID"]);
for (int x = 0; x < 10; x++)
{
DataRow customer = tb1.NewRow();
customer[0] = "CustomerID:" + x.ToString();
customer[1] = "Company:" + x.ToString();
tb1.Rows.Add (customer);
for (int y = 0; y < 5; y++)
{
DataRow order = tb2.NewRow();
order[0] = "CustomerID:" + x.ToString();
order [1] = (y + 1) * 1000;
order[2] = DateTime.Now;
tb2.Rows.Add(order);
}
}
return ds;
}