LINQ to SQL的震撼
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
相关文章