LINQ to SQL的震撼
【IT168技术文档】
都说LINQ(Language Integrated Query)是.NET 3.5中最酷的特性。今天在Visual Studio 2008 Express里尝试了一下,感觉十分震撼!
首先简单地说一下LINQ是干什么的:
* 在任何数据源上高效地表达查询行为;
* 将查询结果转换或形成任何形式的结果集;
* 非常方便地操作这个结果集。
对LINQ这个概念不熟悉的同学可以先看这个例子:
输出结果:using System; using System.Collections.Generic; using System.Linq; namespace SimpleLinq { class Program { static void Main(string[] args) { int[] dataSource = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; IEnumerable<int> lessThan5 = from number in dataSource where number > 2 && number < 8 orderby number descending select number; foreach(int number in lessThan5) { Console.WriteLine(number.ToString()); } Console.ReadLine(); } } }
关键就是这一句:from number in dataSource where number > 2 && number < 8 orderby number descending select number。顾名思义即可,无需多说。7 6 5 4 3
下面是想要演示的LINQ to SQL和ORM(Object-relational mapping)。
1. 打开Visual Web Developer 2008(没有的在这里下载),新建一个网站:

2. 然后将SQL Server 2000的示例数据库NorthWind放到App_Data目录下(没有这个数据库的到这里下载):

3. 下面在App_Code文件夹里创建一个Northwind.dbml文件,这个文件用来包含LINQ to SQL的data model,即一些ORM的信息。

4. 下面生成Northwind数据库的data model,在Database Explorer中将Products和Supliers两张表拖入Northwind.dbml的设计视图即可。注意两张表之间存在一定的关系:

5. 在Default.aspx中创建一个GridView,用来显示数据:
6. 在Default.aspx.cs中,我们把符合条件的那些Product查出来(查询条件是Product的Suplier位于USA),查询结果按照ProductName字段的字母顺序排序,然后把结果绑定到GridView:<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>LINQ to SQL</title> </head> <body> <form id="form" runat="server"> <div> <asp:GridView ID="gridView" runat="server" /> </div> </form> </body> </html>
请注意这一句:where product.Supplier.Country == "USA"。using System; using System.Linq; using System.Web.UI; public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { NorthwindDataContext northwind = new NorthwindDataContext(); gridView.DataSource = from product in northwind.Products where product.Supplier.Country == "USA" orderby product.ProductName select product; gridView.DataBind(); } }
至此已经大功告成,运行Default.aspx可以看到结果。整个过程中没有写任何SQL语句来查询数据,甚至没有给出数据库的连接字符串!
可能有的同学会关心查询具体是如何实现的。通过设置断点,可以看到运行时的查询实现:
0
相关文章