zoukankan      html  css  js  c++  java
  • 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();

             }
         }
    }

  • 相关阅读:
    Manjaro 安装 VMware Pro 15
    RAID-0-10 搭建和使用
    列表的切换按钮,是什么实现的?
    动态表单的设计
    如何修改自定义表单的名字,不适用diyname,直接使用id
    php关于批量替换的测试
    fastadmin删除控制器,删除菜单,提示not found
    fastadmin自定义表单,如何根据字段信息,创建表,而且,可以随时修改字段的顺序
    fastadmin如何获取新增后的id,这个可以使用模型的钩子函数。
    fastadmin如何在弹窗内跳转?以及如何在非弹窗页面,做tab选项卡
  • 原文地址:https://www.cnblogs.com/candl/p/4142519.html
Copyright © 2011-2022 走看看