首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> Oracle 資料庫 >> Oracle 教學

ADO.NET DataSet 關聯關係(DataRelation)完整教學:以 Northwind 客戶-訂單為例

     編輯:Oracle 教學

核心概念

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();
        }
    }
}

關鍵 API 說明

  • DataSet.Relations.Add(name, parentCol, childCol):建立一對多關聯。
  • DataRow.GetChildRows(relation):取得子資料列集合。
  • DataRow.GetParentRow(relation):取得父資料列(多對一)。
  • 關聯名稱儲存在 DataSet.Relations 集合中,可透過字串或物件參考。

進階用法

  • 巢狀關聯:可串聯多層(如 Customer → Order → OrderDetail)。
  • 條件約束:關聯建立後可搭配 ForeignKeyConstraint 強制完整性。
  • XML 序列化:DataSet.WriteXml 會保留關聯結構,適合離線資料交換。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved