DataSet中的relation
DataSet中的relation
DataSet是ADO.Net中相當重要的數據訪問模型。有一個很大的優點是可以記錄多個表之間的關系。有點類似與數據庫的外鍵。
在DataSet中也可以定義類似的關系。DataSet有一個屬性Relation,是DataRelation對象的集合,要創建新的關系,可以使用Relation的Add()方法。下面以NorthWind為例,說明這個過程:
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace DataSetRelationStudy
{
??? ?class Program
??? ?{
??????? ?static void Main(string[] args)
??????? ?{
??????????? ?SqlConnection conn = new SqlConnection(@"Data Source=(local);Initial Catalog=Northwind;Integrated Security=True");
??????????? ?//生成一個DataSet用來接受從數據庫來的表,DataSet本身可以看做一個“內存中的數據庫”
??????????? ?DataSet myDs = new DataSet();
??????????? ?//用兩個數據適配器訪問數據庫
??????????? ?SqlDataAdapter custAdapter = new SqlDataAdapter("SELECT * FROM Customers", conn);
??????????? ?SqlDataAdapter orderAdapter = new SqlDataAdapter("SELECT * FROM Orders", conn);
??????????? ?//將取得的數據存入DataSet中兩個表
??????????? ?custAdapter.Fill(myDs, "Customers");
??????????? ?orderAdapter.Fill(myDs, "Orders");
??????????? ?//在Customers表和Orders之間定義關系,實現“一對多”關系
??????????? ?//其中Customers 是 父表,是一對多中的“一”
??????????? ?//Orders 是子表,是一對多中的 “多”
??????????? ?//關系定義的方法是 DataRelation 變量名 = “DataSet對象”.Relations.Add("關系名",DataSet對象.主表.列名 , DataSet對象.子表.列名);
??????????? ?//這樣便在兩張表之間建立了一對多關系,相當于“外鍵”
??????????? ?//利用關系可以方便的在兩表之間導航
??????????? DataRelation custOrderRelation = myDs.Relations.Add("CustOrders",
??????????????? ?myDs.Tables["Customers"].Columns["CustomerID"], myDs.Tables["Orders"].Columns["CustomerID"]);
?
??????????? ?foreach (DataRow custRow in myDs.Tables["Customers"].Rows)//利用關系來查找Customers表中每個人的訂單
??????????? ?{
??????????????? ?Console.WriteLine(" Custeomer ID: "+custRow["CustomerID"]+" Name: "+custRow["CompanyName"]);
??????????????? ?//下面是關鍵,主表中的行可以用 行.GetChildRows(關系變量) 來取得子表中的相關行
??????????????? ?//可以用 行.GetChildRows("關系名稱") 調用,名稱是存在DataSet的Relations屬性中的名字
??????????????? ?//返回的是一個DataRow的集合,可以遍歷這個集合來取得所有的子項
??????????????? ?//foreach(DataRow orderRow in custRow.GetChildRows(custOrderRelation))
??????????????? foreach(DataRow orderRow in custRow.GetChildRows("CustOrders"))
??????????????? ?{
??????????????????? ?Console.WriteLine(" Order ID: "+orderRow["OrderID"]);
??????????????? ?}
??????????? ?}
??????????? ?conn.Close();
??????????? ?Console.Read();
??????? ?}
??? ?}
}
轉載于:https://www.cnblogs.com/candl/p/4142519.html
總結
以上是生活随笔為你收集整理的DataSet中的relation的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 实现在tabcontrol里面拖拽tab
- 下一篇: 全排列的几个方法