日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

DataSet中的relation

發布時間:2025/3/20 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。