DataSet 可在記憶體中建立多個 DataTable 並透過 DataRelation 定義父子關聯(類似資料庫外鍵),支援導覽、篩選、層級顯示等操作。
using System;
using System.Data;
using System.Data.SqlClient;
namespace DataSetRelationStudy
{
class Program
{
static void Main(string[] args)
{
string connStr = @"Data Source=(local);Initial Catalog=Northwind;Integrated Security=True";
using (SqlConnection conn = new SqlConnection(connStr))
{
DataSet ds = new DataSet();
// 1. 取得兩張表
SqlDataAdapter custAdapter = new SqlDataAdapter("SELECT * FROM Customers", conn);
SqlDataAdapter orderAdapter = new SqlDataAdapter("SELECT * FROM Orders", conn);
custAdapter.Fill(ds, "Customers");
orderAdapter.Fill(ds, "Orders");
// 2. 建立關聯:Customers(父) -> Orders(子)
DataRelation rel = ds.Relations.Add("CustOrders",
ds.Tables["Customers"].Columns["CustomerID"],
ds.Tables["Orders"].Columns["CustomerID"]);
// 3. 利用關聯導覽:列出每位客戶的訂單
foreach (DataRow custRow in ds.Tables["Customers"].Rows)
{
Console.WriteLine($"Customer ID: {custRow["CustomerID"]} Name: {custRow["CompanyName"]}");
foreach (DataRow orderRow in custRow.GetChildRows(rel)) // 或 GetChildRows("CustOrders")
{
Console.WriteLine($" Order ID: {orderRow["OrderID"]}");
}
}
}
Console.Read();
}
}
}
DataSet.Relations.Add(name, parentCol, childCol):建立一對多關聯。DataRow.GetChildRows(relation):取得子資料列集合。DataRow.GetParentRow(relation):取得父資料列(多對一)。DataSet.Relations 集合中,可透過字串或物件參考。ForeignKeyConstraint 強制完整性。DataSet.WriteXml 會保留關聯結構,適合離線資料交換。