Home > Articles > Programming > Windows Programming

This chapter is from the book

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020