Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Lesson 2: executing Queries using LinQ to sQL In the previous lesson, you were introduced to the LINQ to SQL designer, the DataContext class, and an example entity class. In addition, a couple of LINQ to SQL queries were present- ed to demonstrate the operation of the DataContext class and lazy loading. You also saw how the LINQ to SQL provider queries only for the required data when where clauses are provided. This lesson examines some of the more common types of LINQ to SQL queries you might perform. After this lesson, you will be able to: Perform LINQ to SQL queries with filtering and sorting. Write LINQ to SQL statements that implement projections. Perform inner joins with LINQ to SQL. Perform outer joins with LINQ to SQL. Create and execute grouping and aggregation with LINQ to SQL. Estimated lesson time: 45 minutes Basic Query with Filter and Sort Basic queries using the LINQ to SQL classes are very clean and readable. In addition, remem- ber that LINQ to SQL classes retrieve only the data you request. The following code sample queries for a list of customers that contain the word "Restaurant" in the company name, sorted on postal code. Sample of Visual Basic Code Private Sub mnuBasicQuery_Click(ByVal sender As System.Object, _ { ByVal e As System.Windows.RoutedEventArgs) Dim ctx = New NorthwindDataContext() Dim sw = New StringWriter() ctx.Log = sw Dim customers = From c In ctx.Customers Where c.CompanyName.Contains("Restaurant") Order By c.PostalCode Select c dg.ItemsSource = customers MessageBox.Show(sw.GetStringBuilder().ToString()); End Sub Sample of C# Code private void mnuBasicQuery_Click(object sender, RoutedEventArgs e) { var ctx = new NorthwindDataContext(); var sw = new StringWriter(); 260 chapter 4 LINQ to SQL