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.

The answer to the exercise will be included and explained if you attend the Wise Owl course listed below!

Category ==> Visual C Sharp 2010  (65 exercises)
Topic ==> LINQ to SQL models  (1 exercise)
Level ==> Relatively easy
Course ==> Adv C# | Classes & LINQ
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.

Creating a LINQ to SQL model

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.


Using the LINQ to SQL model

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! 

This page has 0 threads Add post