databases and linq - city university of new yorknatacha/teachspring_2013/csc330/labs/... ·...

17
18 Databases and LINQ Now go, write it before them in a table, and note it in a book, that it may be for the time to come for ever and ever. —Isaiah 30:8 It is a capital mistake to theorize before one has data. —Arthur Conan Doyle Objectives In this chapter you’ll learn: The relational database model. To use LINQ to retrieve and manipulate data from a database. To add data sources to projects. To use the Object Relational Designer to create LINQ to SQL classes. To use the IDE’s drag-and- drop capabilities to display database tables in applications. To use data binding to move data seamlessly between GUI controls and databases. To create Master/Detail views that enable you to select a record and display its details. © 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

Upload: vocong

Post on 20-Sep-2018

212 views

Category:

Documents


0 download

TRANSCRIPT

18Databases and LINQ

Now go, write it before them in a table, and note it in a book, that it may be for the time to come for ever and ever. —Isaiah 30:8

It is a capital mistake to theorize before one has data.—Arthur Conan Doyle

O b j e c t i v e sIn this chapter you’ll learn:

■ The relational database model.

■ To use LINQ to retrieve and manipulate data from a database.

■ To add data sources to projects.

■ To use the Object Relational Designer to create LINQ to SQL classes.

■ To use the IDE’s drag-and-drop capabilities to display database tables in applications.

■ To use data binding to move data seamlessly between GUI controls and databases.

■ To create Master/Detail views that enable you to select a record and display its details.

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

Self-Review Exercises 2

Self-Review Exercises18.1 Fill in the blanks in each of the following statements:

a) A table in a relational database consists of and in which values arestored.

ANS: rows, columns. b) The uniquely identifies each row in a relational database table.ANS: primary key. c) A relational database can be manipulated in LINQ to SQL via a(n) object,

which contains properties for accessing each table in the database.ANS: DataContext. d) The control (presented in this chapter) displays data in rows and columns that

correspond to the rows and columns of a data source.ANS: DataGridView. e) Merging data from multiple relational database tables is called the data.ANS: joining. f) A(n) is a column (or group of columns) in a relational database table that

matches the primary-key column (or group of columns) in another table.ANS: foreign key. g) A(n) object serves as an intermediary between a data source and its corre-

sponding data-bound GUI control.ANS: BindingSource. h) The property of a control specifies where it gets the data it displays.ANS: DataSource. i) The clause declares a new temporary variable within a LINQ query.ANS: Let.

18.2 State whether each of the following is true or false. If false, explain why.a) Providing the same value for a foreign key in multiple rows causes the DBMS to report

an error. ANS: False. Multiple rows can have the same value for a foreign key. Providing the same

value for the primary key in multiple rows causes the DBMS to report an error, be-cause duplicate primary keys would prevent each row from being identified uniquely.

b) Providing a foreign-key value that does not appear as a primary-key value in anothertable is an error.

ANS: True. c) The result of a query can be sorted in ascending or descending order.ANS: True. d) A BindingNavigator object can extract data from a database.ANS: False. A BindingNavigator allows users to browse and manipulate data displayed by

another GUI control. A DataContext can extract data from a database. e) LINQ to SQL automatically saves changes made back to the database.ANS: False. You must call the SubmitChanges method of the DataContext to save the

changes made back to the database.

Exercises18.3 (Display Authors Table Application Modification) Modify the DisplayTable application inSection 21.5 to contain a TextBox and a Button that allow the user to search for specific authors bylast name. Include a Label to identify the TextBox. Using the techniques presented in Section 21.9,create a LINQ query that changes the DataSource property of AuthorBindingSource to contain onlythe specified authors.

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

3 Chapter 18 Databases and LINQ

ANS:

1 // Ex. 18.3 Solution: DisplayAuthorsTable.cs2 // Displaying data from a database table in a DataGridView.3 using System;4 using System.Linq;5 using System.Windows.Forms;67 namespace DisplayTable8 {9 public partial class DisplayAuthorsTable : Form

10 {11 // constructor12 public DisplayAuthorsTable()13 {14 DisplayAuthorsTable();15 } // end constructor1617 // LINQ to SQL data context18 private BooksDataContext database = new BooksDataContext();1920 // load data from database into DataGridView21 private void DisplayAuthorsTable_Load( object sender, EventArgs e )22 {23 // use LINQ to order the data for display24 authorBindingSource.DataSource =25 from author in database.Authors26 orderby author.AuthorID27 select author;28 } // end method DisplayAuthorsTable_Load2930 // Click event handler for the Save Button in the31 // BindingNavigator saves the changes made to the data32 private void authorBindingNavigatorSaveItem_Click(33 object sender, EventArgs e )34 {35 Validate(); // validate input fields36 authorBindingSource.EndEdit(); // indicate edits are complete37 database.SubmitChanges(); // write changes to database file38 } // end method authorBindingNavigatorSaveItem_Click3940 // displays only rows that have the specified last name41 private void findButton_Click( object sender, EventArgs e )42 {43 // update DataSource to include only people 44 // with specified last name45 authorBindingSource.DataSource =46 from author in database.Authors47 where author.LastName.StartsWith( findTextBox.Text )48 orderby author.AuthorID49 select author;50 } // end method findButton_Click 51 } // end class DisplayAuthorsTable52 } // end namespace DisplayTable

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

Exercises 4

18.4 (Display Query Results Application Modification) Modify the Display Query Results applica-tion in Section 21.6 to contain a TextBox and a Button that allow the user to perform a search ofthe book titles in the Titles table of the Books database. Use a Label to identify the TextBox. Whenthe user clicks the Button, the application should execute and display the result of a query that selectsall the rows in which the search term entered by the user in the TextBox appears anywhere in theTitle column. For example, if the user enters the search term “Visual,” the DataGridView shoulddisplay the rows for Simply Visual Basic 2008, Visual Basic 2008 How to Program, Visual C# 2008How to Program and Visual C++ 2008 How to Program. If the user enters “Simply,” the DataGrid-View should display only the row for Simply Visual Basic 2008. [Hint: Use the Contains method ofthe String class.]

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

5 Chapter 18 Databases and LINQ

ANS:

1 // Ex. 18.4 Solution: TitleQueries.cs2 // Displaying the result of a user-selected query in a DataGridView.3 using System;4 using System.Linq;5 using System.Windows.Forms;67 namespace DisplayQueryResult8 {9 public partial class TitleQueries : Form

10 {11 // constructor12 public TitleQueries()13 {14 InitializeComponent();15 } // end constructor1617 // LINQ to SQL data context18 private BooksDataContext database = new BooksDataContext();1920 // load data from database into DataGridView21 private void TitleQueries_Load(22 object sender, EventArgs e )23 {24 // write SQL to standard output stream25 database.Log = Console.Out;2627 // set the ComboBox to show the default query that28 // selects all books from the Titles table29 queriesComboBox.SelectedIndex = 0;30 } // end class TitleQueries_Load3132 // Click event handler for the Save Button in the33 // BindingNavigator saves the changes made to the data34 private void titleBindingNavigatorSaveItem_Click(35 object sender, EventArgs e )36 {37 Validate(); // validate input fields38 titleBindingSource.EndEdit(); // indicate edits are complete39 database.SubmitChanges(); // write changes to database file4041 // when saving, return to "all titles" query42 queriesComboBox.SelectedIndex = 0;43 } // end method titleBindingNavigatorSaveItem_Click4445 // loads data into titleBindingSource based on user-selected query46 private void queriesComboBox_SelectedIndexChanged(47 object sender, EventArgs e )48 {49 // set the data displayed according to what is selected50 switch ( queriesComboBox.SelectedIndex )51 {

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

Exercises 6

52 case 0: // all titles53 // use LINQ to order the books by title54 titleBindingSource.DataSource =55 from title in database.Titles56 orderby title.Title157 select title;58 break;59 case 1: // titles with 2008 copyright60 // use LINQ to get titles with 200861 // copyright and sort them by title62 titleBindingSource.DataSource =63 from title in database.Titles64 where title.Copyright == "2008"65 orderby title.Title166 select title;67 break;68 case 2: // titles ending with "How to Program"69 // use LINQ to get titles ending with70 // "How to Program" and sort them by title71 titleBindingSource.DataSource =72 from title in database.Titles73 where title.Title1.EndsWith( "How to Program" )74 orderby title.Title175 select title;76 break;77 } // end switch7879 titleBindingSource.MoveFirst(); // move to first entry80 } // end method queriesComboBox_SelectedIndexChanged8182 // display only titles that contain the search term83 private void findButton_Click( object sender, EventArgs e )84 {85 // filter titles based on search term in findTextBox86 titleBindingSource.DataSource =87 from title in database.Titles88 where title.Title1.Contains( findTextBox.Text )89 orderby title.Title190 select title;91 } // end method findButton_Click92 } // end class TitleQueries93 } // end namespace DisplayQueryResult

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

7 Chapter 18 Databases and LINQ

18.5 (Baseball Database Application) Build an application that executes a query against thePlayers table of the Baseball database included in the Databases folder with this chapter’s exam-ples. Display the table in a DataGridView, and add a TextBox and Button to allow the user to searchfor a specific player by last name. Use a Label to identify the TextBox. Clicking the Button shouldexecute the appropriate query.

ANS:

1 // Ex. 18.5 Solution: BaseballPlayersForm.cs2 // Displays the Players table of the Baseball database in a DataGridView3 // and allows the user to search for players by last name.4 using System;

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

Exercises 8

5 using System.Linq;6 using System.Windows.Forms;78 namespace BaseballPlayers9 {

10 public partial class BaseballPlayersForm : Form11 {12 // constructor13 public BaseballPlayersForm()14 {15 InitializeComponent();16 } // end constructor1718 // database connection19 private BaseballDataContext database = new BaseballDataContext();2021 // load the data from the database when the Form loads22 private void BaseballPlayersForm_Load( object sender, EventArgs e )23 {24 // fill the DataGridView with the player information25 playerBindingSource.DataSource =26 from player in database.Players27 orderby player.PlayerID28 select player;29 } // end method BaseballPlayersForm_Load3031 // Click event handler for the Save Button in the32 // BindingNavigator saves the changes made to the data33 private void playerBindingNavigatorSaveItem_Click(34 object sender, EventArgs e )35 {36 Validate(); // validate input fields37 playerBindingSource.EndEdit(); // indicate edits are complete38 database.SubmitChanges(); // write changes to database file39 } // end method playerBindingNavigatorSaveItem_Click4041 // filter to display only players with the selected last name42 private void findButton_Click( object sender, EventArgs e )43 {44 // include only players that have the last name in findTextBox45 playerBindingSource.DataSource =46 from player in database.Players47 where player.LastName.StartsWith( findTextBox.Text )48 orderby player.PlayerID49 select player;50 } // end method findButton_Click51 } // end class BaseballPlayersForm52 } // end namespace BaseballPlayers

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

9 Chapter 18 Databases and LINQ

18.6 (Baseball Database Application Modification) Modify Exercise 18.5 to allow the user tolocate players with batting averages in a specific range. Add a minimumTextBox for the minimum bat-ting average (0.000 by default) and a maximumTextBox for the maximum batting average (1.000 bydefault). Use a Label to identify each TextBox. Add a Button for executing a query that selects rowsfrom the Players table in which the BattingAverage column is greater than or equal to the specifiedminimum value and less than or equal to the specified maximum value.

ANS:

1 // Ex. 18.6 Solution: BaseballPlayersForm.cs2 // Displays the Players table of the Baseball database in a DataGridView3 // and allows the user to search for players by name or batting average.4 using System;5 using System.Linq;

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

Exercises 10

6 using System.Windows.Forms;78 namespace BaseballPlayers9 {

10 public partial class BaseballPlayersForm : Form11 {12 // constructor13 public BaseballPlayersForm()14 {15 InitializeComponent();16 } // end constructor1718 // database connection19 private BaseballDataContext database = new BaseballDataContext();2021 // load the data from the database when the Form loads22 private void BaseballPlayersForm_Load( object sender, EventArgs e )23 {24 // fill the DataGridView with the player information25 playerBindingSource.DataSource =26 from player in database.Players27 orderby player.PlayerID28 select player;29 } // end method BaseballPlayersForm_Load3031 // Click event handler for the Save Button in the32 // BindingNavigator saves the changes made to the data33 private void playerBindingNavigatorSaveItem_Click(34 object sender, EventArgs e )35 {36 Validate(); // validate input fields37 playerBindingSource.EndEdit(); // indicate edits are complete38 database.SubmitChanges(); // write changes to database file39 } // end method playerBindingNavigatorSaveItem_Click4041 // filter to display only players with the selected last name42 private void findButton_Click( object sender, EventArgs e )43 {44 // include only players that have the last name in findTextBox45 playerBindingSource.DataSource =46 from player in database.Players47 where player.LastName.StartsWith( findTextBox.Text )48 orderby player.PlayerID49 select player;50 } // end method findButton_Click5152 // filter to display only players with53 // batting averages in the specified range54 private void averageButton_Click( object sender, EventArgs e )55 {56 // convert strings in TextBoxes to decimals57 decimal minimum = Convert.ToDecimal( minimumTextBox.Text );58 decimal maximum = Convert.ToDecimal( maximumTextBox.Text );59

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

11 Chapter 18 Databases and LINQ

18.7 (Project: AdventureWorks Sample Database) In this exercise, use Microsoft’s sampleAdventureWorks database. There are several versions available, depending on what version of SQLServer you’re using and your operating system. We used the AdventureWorks LT version of the da-tabase—a smaller version with fewer tables and less data than the full version. The files for SQLServer 2008 can be downloaded from

60 // use LINQ to select only players in the range given in61 // minimumTextBox and maximumTextBox62 playerBindingSource.DataSource =63 from player in database.Players64 where player.BattingAverage >= minimum65 && player.BattingAverage <= maximum66 orderby player.PlayerID67 select player;68 } // end method averageButton_Click69 } // end class BaseballPlayersForm70 } // end namespace BaseballPlayers

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

Exercises 12

msftdbprodsamples.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24854

The installer allows you to select which version of the database to install. Use the AdventureWorks database in an application that runs multiple queries on the database

and displays the results. First, it should list customers and their addresses. As this is a large list, limitthe number of results to ten. [Hint: Use LINQ’s Take clause at the end of the query to return a lim-ited number of results. The Take clause consists of the Take operator, then an Integer specifyinghow many rows to take.] Second, if a category has subcategories, the output should show the cate-gory with its subcategories indented below it. The queries described here require the Adventure-Works tables Address, Customer, CustomerAddress and ProductCategory.

ANS:

1 // Ex. 18.7 Solution: AdventureWorks.cs2 // Using LINQ to aggregate data from multiple3 // tables in the AdventureWorks database.4 using System;5 using System.Linq;67 namespace AdventureWorks8 {9 public class AdventureWorks

10 {11 public static void Main( string[] args )12 {13 // create the database connection14 AdventureWorksDataContext database =15 new AdventureWorksDataContext();1617 // use LINQ to retrieve first 10 customer-address pairs18 var customersAndAddresses =19 from customerAndAddress in database.CustomerAddresses20 let customer = customerAndAddress.Customer21 let address = customerAndAddress.Address22 select new23 {24 Name = customer.FirstName + " " + customer.LastName,25 Address = string.Format( "{0}, {1}, {2} {3}",26 address.AddressLine1, address.City,27 address.StateProvince, address.PostalCode )28 };2930 // display customers and addresses31 foreach ( var element in customersAndAddresses.Take( 10 ) )32 {33 Console.WriteLine( "{0,-20} {1}",34 element.Name, element.Address );35 } // end foreach3637 Console.WriteLine(); // blank line for readability38

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

13 Chapter 18 Databases and LINQ

39 // use LINQ to retrieve categories with subcategories40 // include only categories with subcategories41 var categories =42 from category in database.ProductCategories43 let children = category.ProductCategories44 where children.Any()45 select new46 {47 category.Name,48 Children = ( from child in children select child.Name )49 };5051 // display categories and their subcategories52 foreach ( var category in categories )53 {54 // display category name55 Console.WriteLine( category.Name + ":" );5657 foreach ( var child in category.Children )58 {59 // display subcategory name60 Console.WriteLine( "\t" + child );61 } // end inner foreach62 } // end outer foreach63 } // end Main64 } // end class AdventureWorks65 } // end namespace AdventureWorks

Orlando Gee 2251 Elliot Avenue, Seattle, Washington 98104Keith Harris 7943 Walnut Ave, Renton, Washington 98055Keith Harris 3207 S Grady Way, Renton, Washington 98055Donna Carreras 12345 Sterling Avenue, Irving, Texas 75061Janet Gates 800 Interchange Blvd., Austin, Texas 78701Janet Gates 165 North Main, Austin, Texas 78701Lucy Harrington 482505 Warm Springs Blvd., Fremont, California 94536Rosmarie Carroll 39933 Mission Oaks Blvd, Camarillo, California 93010Dominic Gash 5420 West 22500 South, Salt Lake City, Utah 84101Kathleen Garza 6388 Lake City Way, Burnaby, British Columbia V5A 3A6

Bikes: Mountain Bikes Road Bikes Touring BikesComponents: Handlebars Bottom Brackets Brakes Chains Cranksets Derailleurs Forks Headsets Mountain Frames Pedals Road Frames

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

Exercises 14

18.8 (Project: AdventureWorks Master/Detail view) Use the Microsoft AdventureWorks databasefrom Exercise 18.7 to create a master/detail view. One master list should be customers, and the oth-er should be products—these should show the details of products the customers purchased, and cus-tomers who purchased those products, respectively. Note that there are many customers in thedatabase who did not order any products, and many products that no one ordered. Restrict thedrop-down lists so that only customers that have submitted at least one order and products that havebeen included in at least one order are displayed. The queries in this exercise require the Customer,Product, SalesOrderHeader and SalesOrderDetail tables.

ANS:

Saddles Touring Frames WheelsClothing: Bib-Shorts Caps Gloves Jerseys Shorts Socks Tights VestsAccessories: Bike Racks Bike Stands Bottles and Cages Cleaners Fenders Helmets Hydration Packs Lights Locks Panniers Pumps Tires and Tubes

1 // Ex. 18.8 Solution: AdventureWorksMasterDetailForm.cs2 // A master/detail view using the AdventureWorks database.3 using System;4 using System.Linq;5 using System.Windows.Forms;67 namespace AdventureWorksMasterDetail8 {9 public partial class AdventureWorksMasterDetailForm : Form

10 {11 // constructor 12 public AdventureWorksMasterDetailForm()13 {14 InitializeComponent();15 } // end constructor16

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

15 Chapter 18 Databases and LINQ

17 // connection to the database18 private AdventureWorksDataContext database =19 new AdventureWorksDataContext();2021 // this class allows us to show the22 // customer's full name in the ComboBox23 private class CustomerBinding24 {25 public Customer Customer { get; set; } // contained customer26 public string Name { get; set; } // customer's full name27 } // end class CustomerBinding2829 // initialize data sources when the form is loaded30 private void AdventureWorksMasterDetailForm_Load( 31 object sender, EventArgs e )32 {33 customerComboBox.DisplayMember = "Name"; // display full name3435 // set the customerComboBox's DataSource 36 // to the list of customers37 customerComboBox.DataSource =38 from customer in database.Customers39 where customer.SalesOrderHeaders.Any()40 orderby customer.LastName, customer.FirstName41 let name = customer.FirstName + " " + customer.LastName42 select43 new CustomerBinding { Customer = customer, Name = name };4445 // display product's name46 productComboBox.DisplayMember = "Name";4748 // set the productComboBox's DataSource to the list of products49 productComboBox.DataSource =50 from product in database.Products51 where product.SalesOrderDetails.Any()52 orderby product.Name53 select product;5455 // initially, display no "detail" data56 adventureWorksBindingSource.DataSource = null;5758 // set the DataSource of the DataGridView to the BindingSource59 adventureWorksDataGridView.DataSource =60 adventureWorksBindingSource;61 } // end method AdventureWorksMasterDetailForm_Load6263 // display products that the customer purchased64 private void customerComboBox_SelectedIndexChanged(65 object sender, EventArgs e )66 {67 // get the selected Customer object from the ComboBox68 Customer currentCustomer =69 ( ( CustomerBinding ) customerComboBox.SelectedItem )70 .Customer;

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

Exercises 16

7172 // traverse the order tables to get73 // products the customer ordered74 adventureWorksBindingSource.DataSource =75 from header in currentCustomer.SalesOrderHeaders76 from detail in header.SalesOrderDetails77 select detail.Product;78 } // end method customerComboBox_SelectedIndexChanged7980 // display customers that purchased a specific product81 private void productComboBox_SelectedIndexChanged(82 object sender, EventArgs e )83 {84 // get the selected Product object from the ComboBox85 Product currentProduct =86 ( Product ) productComboBox.SelectedItem;8788 // traverse order tables to get customers89 // that ordered this product90 adventureWorksBindingSource.DataSource =91 from order in currentProduct.SalesOrderDetails92 select order.SalesOrderHeader.Customer;93 } // end method productComboBox_SelectedIndexChanged94 } // end class AdventureWorksMasterDetailForm95 } // end namespace AdventureWorksMasterDetail

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.

17 Chapter 18 Databases and LINQ

© 2011 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.