- 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.6 LINQ to SQL: Extracting Information from a Database
In this section, we demonstrate how to connect to a database, query it and display the result of the query. There is little code in this section—the IDE provides visual programming tools and wizards that simplify accessing data in your projects. These tools establish database connections and create the data-binding objects necessary to view and manipulate the data through Windows Forms GUI controls.
The next example performs a simple query on the Books database from Section 21.3. The program retrieves the entire Authors table and uses data binding to display its data in a DataGridView—a control from namespace System.Windows.Forms that can display a data source in a GUI. First, we connect to the Books database and create the LINQ to SQL classes required to use it. Then, we add the Authors table as a data source. Finally, we drag the Authors table data source onto the Design view to create a GUI for displaying the table’s data.
21.6.1 Creating LINQ to SQL Classes
This section presents the steps required to create LINQ to SQL classes for a database. Though we create a Windows Forms Application here, Steps 2–3 apply to any type of application that manipulates a database via LINQ to SQL.
Step 1: Creating the Project
Create a new Windows Forms Application named DisplayTable. Change the name of the source file to DisplayTableForm.cs. When the IDE asks if you wish to update the Form’s class name to match the source file, select Yes. Set the Form’s Text property to DisplayTable.
Step 2: Adding a Database to the Project
To interact with a database, you must first add it to the project. Select Tools > Connect to Database.... If the Choose Data Source dialog appears, select Microsoft SQL Server Database File from the Data source: ListBox. If you check the Always use this selection CheckBox, Visual C# will use this type of database file by default when you add databases to your projects in the future. Click Continue to open the Add Connection dialog. Notice that the Data source: TextBox reflects your selection in the Choose Data Source dialog. You can click the Change... Button to select a different type of database. Next, click Browse... and locate the Books.mdf file in the Databases directory included with this chapter’s examples. You can click Test Connection to verify that the IDE can connect to the database through SQL Server Express. Click OK to create the connection.
Step 3: Generating the LINQ to SQL classes
After the database has been added, you must create the classes based on the database schema. To do this, right click the project name in the Solution Explorer and select Add > New Item... to display the Add New Item dialog. Select LINQ to SQL classes, name the new item Books.dbml and click the Add button. After a few moments, the Object Relational Designer window appears. You can also double click the Books.dbml file in the Solution Explorer to open the Object Relational Designer.
The Database Explorer window, which lets you navigate the structure of databases, should have appeared on the left side of the IDE when you added the database to the project. If not, open it by selecting View > Other Windows > Database Explorer. Expand the Books.mdf database node, then expand the Tables node. Drag the Authors, Titles and AuthorISBN tables onto the Object Relational Designer. The IDE prompts whether you want to copy the database to the project directory. Select Yes. Then save the Books.dbml file. At this point, the IDE generates the LINQ to SQL classes—the next steps will not work if you do not save the .dbml file.
21.6.2 Creating Data Bindings
While they are not a part of LINQ to SQL, the automatic data bindings that the IDE provides greatly simplify the creation of applications to view and modify the data stored in the database’s tables. You must write a small amount of code to bridge the gap between the autogenerated data-binding classes and the autogenerated LINQ to SQL classes.
Step 1: Adding a Data Source
To use the LINQ to SQL classes in our bindings, we must first add them as a data source. Select Data > Add New Data Source... to display the Data Source Configuration Wizard. Since the LINQ to SQL classes can be used to create objects representing the tables in the database, we’ll use an object data source. In the dialog, select Object and click Next >. Expand the tree view in the next screen and select DisplayTable > DisplayTable > Author. The first DisplayTable is the project’s name, the second is the DisplayTable namespace where the automatically generated classes are located, and the last is the Author class—an object of this class will be used as the data source. Click Next > then Finish. The Authors table in the database is now a data source that can be used by the bindings.
Step 2: Create GUI Elements
Open the Data Sources window by selecting Data > Show Data Sources. The Author class that you added in the previous step should appear. The columns of the Authors table should appear below it, as well as an AuthorISBNs entry showing the relationship between the two tables.
Open the DisplayTableForm in Design view. Click the Author node in the Data Sources window—it should change to a drop-down list. Open the drop-down and ensure that the DataGridView option is selected—this is the GUI control that will be used to display and interact with the data.
Drag the Author node from the Data Sources window to the DisplayTableForm. The IDE creates a DataGridView with the correct column names and a BindingNavigator. The BindingNavigator contains Buttons for moving between entries, adding entries, deleting entries and saving changes to the database. The IDE also generates a BindingSource, which transfers data between the data source and the data-bound controls on the Form. Nonvisual components such as the BindingSource and the nonvisual aspects of the BindingNavigator appear in the component tray—the gray region below the Form in Design view (Fig. 21.23). We use the default names for automatically generated components throughout this chapter to show exactly what the IDE creates, but we have made small modifications to the layout such as setting the DataGridView’s Dock property to Fill so it fills the Form. These modifications have no effect on the behavior of the program, and are simply cosmetic—you may also want to tweak the GUI to suit your tastes.
Fig. 21.23 Component tray holds nonvisual components in Design view.
Step 3: Connect the BooksDataContext to the AuthorBindingSource
Now that we’ve created the back-end LINQ to SQL classes and the front-end DataGridView and BindingNavigator, we must connect them with a small amount of code. The DataGridView is already connected to the BindingSource by the IDE, so we simply need to connect the BooksDataContext you declared in the previous section and the authorBindingSource you created above. Figure 21.24 shows the small amount of code needed to move data back and forth between the database and GUI.
Fig. 21.24 Displaying data from a database table in a DataGridView.
1 // Fig. 21.24: DisplayTableForm.cs 2 // Displaying data from a database table in a DataGridView. 3 using System; 4 using System.Linq; 5 using System.Windows.Forms; 6 7 namespace DisplayTable 8 { 9 public partial class DisplayTableForm : Form 10 { 11 // constructor 12 public DisplayTableForm() 13 { 14 InitializeComponent(); 15 } // end constructor 16 17 // LINQ to SQL data context 18 private BooksDataContext database = new BooksDataContext(); 19 20 // load data from database into DataGridView 21 private void DisplayTableForm_Load( object sender, EventArgs e ) 22 { 23 // use LINQ to order the data for display 24 authorBindingSource.DataSource = 25 from author in database.Authors 26 orderby author.AuthorID 27 select author; 28 } // end method DisplayTableForm_Load 29 30 // click event handler for the Save Button in the 31 // BindingNavigator saves the changes made to the data 32 private void authorBindingNavigatorSaveItem_Click( 33 object sender, EventArgs e ) 34 { 35 Validate(); // validate input fields 36 authorBindingSource.EndEdit(); // indicate edits are complete 37 database.SubmitChanges(); // write changes to database file 38 } // end method authorBindingNavigatorSaveItem_Click 39 } // end class DisplayTableForm 40 } // end namespace DisplayTable
As mentioned in the previous section, we must use a DataContext object to interact with the database. The BooksDataContext class is automatically generated by the IDE to allow access to the Books database. Line 18 defines an object of this class named database.
Create the Form’s Load handler by double clicking the title bar in Design view. We allow data to move between the DataContext and the BindingSource by creating a LINQ query that extracts data from the DataContext’s Authors property (lines 25–27), which corresponds to the Authors table in the database. The BindingSource’s DataSource property is set to the results of this query (line 24). The BindingSource uses its DataSource to extract data from the database and to populate the DataGridView.
Step 4: Saving Modifications Back to the Database
We’d like to save data back to the database if the user modifies it. By default, the Binding-Navigator’s save Button () is disabled. Enable it via the save Button’s right-click menu or by using the Properties window to set its Enabled property to True. Then, double click the Button to create its event handler.
Saving the data entered into the DataGridView back to the database is a three-step process (lines 35–37). First, all controls on the form are validated (line 35)—if any of the controls have validation event handlers, those execute to determine whether the controls’ contents are valid. Second, line 36 calls EndEdit on the BindingSource, which forces it to save any pending changes to its DataSource. Finally, with the data saved back to the LINQ to SQL classes, we call SubmitChanges on the BooksDataContext to store the changes in the database. For efficiency reasons, LINQ to SQL sends only data that has changed.
Step 5: Configuring the Database File to Persist Changes
By default, the original database file is copied to the project’s bin directory—the location of the program’s executable—each time you execute the program. To persist changes between program executions, select the database in the Solution Explorer and set the Copy to Output Directory property in the Properties window to Copy if newer.
Testing the Application
Run the application to verify that it works. The DataGridView should be filled with the author data, as shown in the screenshot. You can add and remove rows, and save your changes back to the database. Note that NULL values are not allowed in the database, and the data bindings consider an empty cell in the DataGridView to be NULL, not an empty string. Therefore, attempting to save the data with some of the fields empty will cause an exception to be thrown.