Visual C# | Entity Frameworks exercise | Use LINQ to SQL to list authors and their count of books

This exercise is provided to allow potential course delegates to choose the correct Wise Owl Microsoft training course, and may not be reproduced in whole or in part in any format without the prior written consent of Wise Owl.

Software ==> Visual C#  (79 exercises)
Version ==> Any version of C#
Topic ==> Entity Frameworks  (1 exercise)
Level ==> Relatively easy
Subject ==> C# training
Before you can do this exercise, you'll need to download and unzip this file (if you have any problems doing this, click here for help).

You need a minimum screen resolution of about 700 pixels width to see our exercises. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.

If you haven't already done so, go into SQL Server Management Studio and open the file in the above folder and run its script.  This should generate a Books database.

Add a new LINQ to SQL classes item called Books to your project:

LINQ to SQL Classses item

The item that you should add to your project.


In Server Explorer, create a connection to this database:

The books connection

You should be able to expand the tables to show the tblAuthor and tblBook tables.


Drag these two tables onto your O/R designer window, and rename the tables to get this:

Authors and books

We've renamed the entities, but left all of the properties the same.


Create a new window called frmBooks, and within this create code to list out the authors.  This should use the data context that you've created:

// use the classes in the LINQ to SQL data model

using (BooksDataContext books = new BooksDataContext())



Now use LINQ to SQL to list out all authors with the number of books they've written.  The easiest way to do this is probably to create a new anonymous type with two properties:

  • AuthorName - the first name and last name concatenated (with a space in between)
  • BookCount - the number of books written by the author

This is what you should see accumulated when you run your code:

Final list of authors

For each author you should see in parentheses the number of books they've written.


At this point you should be marvelling at how easy LINQ to SQL is to code! 

You can unzip this file to see the answers to this exercise, although please remember this is for your personal use only.
This page has 0 threads Add post