日期:2014-05-18 浏览次数:21465 次
#region using Directives
using System;
using System.Data; //Use ADO.NET namespace
using System.Data.SqlClient; //Use SQL Server data provider namespace
using System.Collections.Generic;
using System.Linq;
using System.Text;
#endregion
namespace DataRelation
{
class Program
{
static void Main(string[] args)
{
SqlConnection thisConnection = new SqlConnection("user id=pos;PWD=PO$$IBLE;Server=192.168.2.44;DataBase=gdbranch;TimeOut=30;");
SqlDataAdapter thisAdapter = new SqlDataAdapter(
"SELECT CustomerID,Customername from Customers", thisConnection);
SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter);
DataSet thisDataSet = new DataSet();
SqlDataAdapter custAdapter=new SqlDataAdapter(
"Select * from customers",thisConnection);
SqlDataAdapter orderAdapter=new SqlDataAdapter(
"SELECT * FROM Orders",thisConnection);
custAdapter.Fill(thisDataSet,"Customers");
orderAdapter.Fill(thisDataSet,"Orders");
DataRelation custOrderRel = thisDataSet.Relations.Add("CustOrders",
thisDataSet.Tables["Customers"].Columns["CustomerID"],
thisDataSet.Tables["Orders"].Columns["CustomerID"]);
foreach(DataRow custRow in thisDataSet.Tables["Customers"].Rows)
{
Console.WriteLine("Customer ID:"+custRow["CustomerID"]+
"Name:"+custRow["CompanyName"]);
foreach (DataRow orderRow in custRow.GetChildRows(custOrderRel))
{
Console.WriteLine(" Order ID:"+orderRow["OrderID"]);
}
}
thisConnection.Close();
Console.Write("Program finished,press Enter/Return to continue:");
Console.ReadLine();
}
}
}
DataRelation custOrderRel = thisDataSet.Relations.Add("CustOrders",
thisDataSet.Tables["Customers"].Columns["CustomerID"],
thisDataSet.Tables["Orders"].Columns["CustomerID"]);