- 21.1 Introduction
- 21.2 Relational Databases
- 21.3 Relational Database Overview: Books Database
- 21.4 SQL
- 21.5 LINQ to SQL
- 21.6 LINQ to SQL: Extracting Information from a Database
- 21.7 More Complex LINQ Queries and Data Binding
- 21.8 Retrieving Data from Multiple Tables with LINQ
- 21.9 Creating a Master/Detail View Application
- 21.10 Programming with LINQ to SQL: Address-Book Case Study
- 21.11 Wrap-Up
- 21.12 Tools and Web Resources
21.8 Retrieving Data from Multiple Tables with LINQ
In the two previous examples, we used data bindings to display data extracted using LINQ to SQL. In this section, we concentrate on LINQ to SQL features that simplify querying and combining data from multiple tables. You’ve already seen the SQL INNER JOIN operator in Section 21.4.4—LINQ to SQL provides similar capabilities and allows more complex operations as well. Figure 21.27 uses LINQ to SQL to combine and organize data from multiple tables.
Fig. 21.27 Using LINQ to perform a join and aggregate data across tables.
1 // Fig. 21.27: JoiningTest.cs 2 // Using LINQ to perform a join and aggregate data across tables. 3 using System; 4 using System.Linq; 5 6 namespace JoiningWithLINQ 7 { 8 public class JoiningTest 9 { 10 public static void Main( string[] args ) 11 { 12 // create database connection 13 BooksDataContext database = new BooksDataContext(); 14 15 // get authors and ISBNs of each book they co-authored 16 var authorsAndISBNs = 17 from author in database.Authors 18 join book in database.AuthorISBNs 19 on author.AuthorID equals book.AuthorID 20 orderby author.LastName, author.FirstName 21 select new { author.FirstName, author.LastName, book.ISBN }; 22 23 Console.WriteLine( "Authors and ISBNs:" ); // display header 24 25 // display authors and ISBNs in tabular format 26 foreach ( var element in authorsAndISBNs ) 27 { 28 Console.WriteLine( "\t{0,-10} {1,-10} {2,-10}", 29 element.FirstName, element.LastName, element.ISBN ); 30 } // end foreach 31 32 // get authors and titles of each book they co-authored 33 var authorsAndTitles = 34 from title in database.Titles 35 from book in title.AuthorISBNs 36 let author = book.Author 37 orderby author.LastName, author.FirstName, title.BookTitle 38 select new { author.FirstName, author.LastName, 39 title.BookTitle }; 40 41 Console.WriteLine( "\nAuthors and titles:" ); // header 42 43 // display authors and titles in tabular format 44 foreach ( var element in authorsAndTitles ) 45 { 46 Console.WriteLine( "\t{0,-10} {1,-10} {2}", 47 element.FirstName, element.LastName, element.BookTitle ); 48 } // end foreach 49 50 // get authors and titles of each book 51 // they co-authored; group by author 52 var titlesByAuthor = 53 from author in database.Authors 54 orderby author.LastName, author.FirstName 55 let name = author.FirstName + " " + author.LastName 56 let titles = 57 from book in author.AuthorISBNs 58 orderby book.Title.BookTitle 59 select book.Title.BookTitle 60 select new { Name = name, Titles = titles }; 61 62 Console.WriteLine( "\nTitles grouped by author:" ); // header 63 64 // display titles written by each author, grouped by author 65 foreach ( var author in titlesByAuthor ) 66 { 67 // display author's name 68 Console.WriteLine( "\t" + author.Name + ":" ); 69 70 // display titles written by that author 71 foreach ( var title in author.Titles ) 72 { 73 Console.WriteLine( "\t\t" + title ); 74 } // end inner foreach 75 } // end outer foreach 76 } // end Main 77 } // end class JoiningTest 78 } // end namespace JoiningWithLINQ
Authors and ISBNs: Greg Ayer 0136053033 Harvey Deitel 0131752421 Harvey Deitel 0132222205 Harvey Deitel 0132404168 Harvey Deitel 0136053033 Harvey Deitel 013605305X Harvey Deitel 013605322X Harvey Deitel 0136151574 Harvey Deitel 0136152503 Paul Deitel 0131752421 Paul Deitel 0132222205 Paul Deitel 0132404168 Paul Deitel 0136053033 Paul Deitel 013605305X Paul Deitel 013605322X Paul Deitel 0136151574 Paul Deitel 0136152503 Dan Quirk 0136151574 Authors and titles: Greg Ayer Simply Visual Basic 2008 Harvey Deitel C How to Program Harvey Deitel C++ How to Program Harvey Deitel Internet & World Wide Web How to Program Harvey Deitel Java How to Program Harvey Deitel Simply Visual Basic 2008 Harvey Deitel Visual Basic 2008 How to Program Harvey Deitel Visual C# 2008 How to Program Harvey Deitel Visual C++ 2008 How to Program Paul Deitel C How to Program Paul Deitel C++ How to Program Paul Deitel Internet & World Wide Web How to Program Paul Deitel Java How to Program Paul Deitel Simply Visual Basic 2008 Paul Deitel Visual Basic 2008 How to Program Paul Deitel Visual C# 2008 How to Program Paul Deitel Visual C++ 2008 How to Program Dan Quirk Visual C++ 2008 How to Program Titles grouped by author: Greg Ayer: Simply Visual Basic 2008 Harvey Deitel: C How to Program C++ How to Program Internet & World Wide Web How to Program Java How to Program Simply Visual Basic 2008 Visual Basic 2008 How to Program Visual C# 2008 How to Program Visual C++ 2008 How to Program Paul Deitel: C How to Program C++ How to Program Internet & World Wide Web How to Program Java How to Program Simply Visual Basic 2008 Visual Basic 2008 How to Program Visual C# 2008 How to Program Visual C++ 2008 How to Program Dan Quirk: Visual C++ 2008 How to Program |
The code combines data from the three tables in the Books database and displays the relationships between the book titles and authors in three different ways. The LINQ to SQL classes used in this example were created using the steps described in Section 21.6.1. As in previous examples, the BooksDataContext object (declared in line 13) is needed to be able to query the database.
The first query in the example (lines 17–21) returns results identical to those in Fig. 21.19. It uses LINQ’s join clause, which functions like SQL’s INNER JOIN operator—the generated SQL is nearly identical to the SQL given earlier in Section 21.4.4. As in the SQL example, only rows with the same AuthorID are joined together. Like the from clause, the join clause introduces a range variable—unlike the from clause, it specifies a criterion for joining. The join clause uses equals instead of the == comparison operator because the join criterion is not an arbitrary Boolean expression—you may only join based on equality. Like nested repetition statements, join clauses cause multiple range variables to be in scope—other clauses can access both range variables to combine data from multiple tables (lines 20–21).
The second query (lines 34–39) gives similar output, but it does not use the join query operator. Operations that would require a join in SQL often do not need one in LINQ to SQL, because it automatically creates properties based on foreign-key relationships. These properties enable you to easily access related rows in other tables. Line 35 uses the generated AuthorISBNs property of the Title class to query only the rows in the AuthorISBN table that link to that row of the Titles table. It does this by using multiple from clauses in the same query. In this example the inner from clause iterates over data related to the outer range variable, but the sequences iterated over may be completely unrelated. As with a join clause, both range variables may be used in later clauses. The author variable created in the let clause (line 36) refers to book.Author, demonstrating the automatically generated link between the AuthorISBN and Authors tables based on the foreign-key relationship between them.
Lines 53–60 contain the final query in the example. Instead of returning a flat result set, with data laid out in relational-style rows and columns, the results from this query are hierarchical. Each element in the results contains the name of an Author and a list of Titles that the author wrote. The LINQ query does this by using a nested query in the second let clause (lines 56–59). The outer query iterates over the authors in the database. The inner query (lines 57–59) takes a specific author and retrieves all titles that the author worked on. It does this by navigating the properties created by the foreign-key relationships in the database. The book range variable represents each pair of AuthorID and ISBN in the AuthorISBN table belonging to the author range variable of the outer query. It accesses the Title property of book to retrieve the row in the Titles table with that ISBN and then uses the BookTitle property to include the title of the book in the results. This list of titles is placed into the Titles property of the anonymous type created in the select clause, which also has a Name property that contains the author’s full name. These results are then displayed using nested foreach statements (lines 65–75).
Relational databases cannot return this kind of hierarchical result set, so, unlike the previous two queries, it would be impossible to write a query like this in SQL. Before LINQ, you’d have had to retrieve the results in a flat table like the other two queries, then transform them into the desired format. LINQ does this work for you, allowing you to ignore the relational storage model and concentrate on the object structure that fits your application.