我们知道在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;
}