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