|
| 1 | +using System; |
| 2 | +using Microsoft.Data.SqlClient; |
| 3 | +using System.Data; |
| 4 | + |
| 5 | +namespace NextResultCS |
| 6 | +{ |
| 7 | + class Program |
| 8 | + { |
| 9 | + static void Main() |
| 10 | + { |
| 11 | + string s = GetConnectionString(); |
| 12 | + SqlConnection c = new SqlConnection(s); |
| 13 | + GetCustomers(c); |
| 14 | + PrintCustomersOrders(c, c); |
| 15 | + Console.ReadLine(); |
| 16 | + } |
| 17 | + |
| 18 | + static DataSet GetCustomers(SqlConnection connection) |
| 19 | + { |
| 20 | + using (connection) |
| 21 | + { |
| 22 | + // <Snippet1> |
| 23 | + // Assumes that connection is a valid SqlConnection object. |
| 24 | + string queryString = |
| 25 | + "SELECT CustomerID, CompanyName FROM dbo.Customers"; |
| 26 | + SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection); |
| 27 | + |
| 28 | + DataSet customers = new DataSet(); |
| 29 | + adapter.Fill(customers, "Customers"); |
| 30 | + // </Snippet1> |
| 31 | + return customers; |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + static void PrintCustomersOrders(SqlConnection customerConnection, SqlConnection orderConnection) |
| 36 | + { |
| 37 | + using (customerConnection) |
| 38 | + using (orderConnection) |
| 39 | + { |
| 40 | + // <Snippet2> |
| 41 | + // Assumes that customerConnection and orderConnection are valid SqlConnection objects. |
| 42 | + SqlDataAdapter custAdapter = new SqlDataAdapter( |
| 43 | + "SELECT * FROM dbo.Customers", customerConnection); |
| 44 | + SqlDataAdapter ordAdapter = new SqlDataAdapter( |
| 45 | + "SELECT * FROM Orders", orderConnection); |
| 46 | + |
| 47 | + DataSet customerOrders = new DataSet(); |
| 48 | + |
| 49 | + custAdapter.Fill(customerOrders, "Customers"); |
| 50 | + ordAdapter.Fill(customerOrders, "Orders"); |
| 51 | + |
| 52 | + DataRelation relation = customerOrders.Relations.Add("CustOrders", |
| 53 | + customerOrders.Tables["Customers"].Columns["CustomerID"], |
| 54 | + customerOrders.Tables["Orders"].Columns["CustomerID"]); |
| 55 | + |
| 56 | + foreach (DataRow pRow in customerOrders.Tables["Customers"].Rows) |
| 57 | + { |
| 58 | + Console.WriteLine(pRow["CustomerID"]); |
| 59 | + foreach (DataRow cRow in pRow.GetChildRows(relation)) |
| 60 | + Console.WriteLine("\t" + cRow["OrderID"]); |
| 61 | + } |
| 62 | + // </Snippet2> |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + static private string GetConnectionString() |
| 67 | + { |
| 68 | + // To avoid storing the connection string in your code, |
| 69 | + // you can retrieve it from a configuration file. |
| 70 | + return "Data Source=(local);Initial Catalog=Northwind;" |
| 71 | + + "Integrated Security=SSPI"; |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments