您的位置:首页 > 其它

随便:LINQ OVER DataSet和ADO.NET的简单例子

2012-03-12 22:50 295 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Data.Linq;

namespace DataRelationExample
{
//使用LINQ OVER DataSet和ADO.NET
class Program
{
static void Main(string[] args)
{
SqlConnection thisConnection = new SqlConnection(@"Data Source=WENGJIXI;" +
@"Initial Catalog=NorthWind;Integrated Security=true;");

thisConnection.Open();

DataSet thisDataSet = new DataSet();
SqlDataAdapter cust = new SqlDataAdapter("select * from Customers", thisConnection);
SqlDataAdapter order = new SqlDataAdapter("select * from Orders", thisConnection);
cust.Fill(thisDataSet, "Customers");
order.Fill(thisDataSet, "Orders");

DataRelation custOrderRel = thisDataSet.Relations.Add("CustOrder", thisDataSet.Tables["Customers"].Columns["CustomerID"], thisDataSet.Tables["Orders"].Columns["CustomerID"]);

//返回泛型类型为DataRow,此方法返回的泛型类型可以用于LINQ表达式或查询上,如下面的LINQ查询。
var customers = thisDataSet.Tables["Customers"].AsEnumerable();
var orders = thisDataSet.Tables["Orders"].AsEnumerable();

//使用LINQ OVER DataSet方法
var preferedCustomers = from c in customers
where c.GetChildRows("CustOrder").Length > 10//DataRow的GetChildRows()方法,返回此行相关联的子行。在此是关联到Orders表上。
orderby c.GetChildRows("CustOrder").Length
select c;

//循环输出每一行
foreach (var item in preferedCustomers)
{
Console.WriteLine("{0} orders: {1} {2}, {3} {4} ", item.GetChildRows("CustOrder").Length, item["CustomerID"], item["CompanyName"], item["City"], item["Region"]);
}

thisConnection.Close();
Console.ReadLine();

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: