今天学习了DataSet中访问多张表的知识,现在记录下来,供以后温习。。。高手就路过吧
DataSet中Relations属性返回DataRelation集合,表示DataSet中各各表之间的关系。
要创建DataRelation ,可以使用DataSet.Relations.Add()方法。可以给该方法传递接受关系的字符串,和两个列(父列在前,子列在后),如:
DataRelation custOrderRel = thisDataSet.Relations.Add("CustOrder", thisDataSet.Tables["Customers"].Columns["CustomerID"], thisDataSet.Tables["Orders"].Columns["CustomerID"]);
然后就可以靠这个关系导航了
我们可以使用DataRow的GetChildRow()方法从父对象导航到子对象的相关联行,给这个方法传递这两个表之间的关系对象,如:
foreach (DataRow custRow in thisDataSet.Tables["Customers"].Rows)
{
Console.WriteLine("CustomerID:{0}\nCustomer Company:{1}", custRow["CustomerID"], custRow["CompanyName"]);
foreach (DataRow orderRow in custRow.GetChildRows(custOrderRel))
{
Console.WriteLine("\t customer orderID:{0}", orderRow["OrderID"]);
}
}
如果想从子对象逆导航到父对象的相关联行,可以使用DataRow的GetParentRow()方法,同样也需要给这个方法传递这两个表之间的关系对象。
下面是课本的一个例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace GetChildRow
{
class Program
{
static void Main(string[] args)
{
SqlConnection thisConnection = new SqlConnection(@"Data Source=WENGJIXI;" +
@"Initial Catalog=NorthWind;" +
@"Integrated Security=true;");
SqlDataAdapter thisAdapter = new SqlDataAdapter("select CustomerID,CompanyName from Customers", thisConnection);
SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter);
DataSet thisDataSet = new DataSet();
SqlDataAdapter custAdapter = new SqlDataAdapter("select * from Customers", thisConnection);
SqlDataAdapter orderAdapter = new SqlDataAdapter("select * from Orders", thisConnection);
custAdapter.Fill(thisDataSet, "Customers");
orderAdapter.Fill(thisDataSet, "Orders");
DataRelation custOrderRel = thisDataSet.Relations.Add("CustOrder", thisDataSet.Tables["Customers"].Columns["CustomerID"], thisDataSet.Tables["Orders"].Columns["CustomerID"]);
foreach (DataRow custRow in thisDataSet.Tables["Customers"].Rows)
{
Console.WriteLine("CustomerID:{0}\nCustomer Company:{1}", custRow["CustomerID"], custRow["CompanyName"]);
foreach (DataRow orderRow in custRow.GetChildRows(custOrderRel))
{
Console.WriteLine("\t customer orderID:{0}", orderRow["OrderID"]);
}
}
thisConnection.Close();
Console.ReadLine();
}
}
}