Chapter 8. Overview of ADO.NET

In this chapter, you are introduced to ADO.NET, the data access technology included with the .NET Framework. You are provided with an overview of the objects in ADO.NET that can be used to access a database. You can use these objects to update and retrieve data from a variety of databases, including Microsoft SQL Server, Oracle, and Microsoft Access.

In this chapter, you will learn

  • How to create database connections

  • How to represent database data with DataSets

  • How to represent database data with DataReaders

  • How to improve database access performance through data caching

The Three Dualities of ADO.NET

ADO.NET is the next generation of Microsoft’s ActiveX Data Objects (ADO). You use the classes in the ADO.NET Framework to retrieve and update database data whenever you create an application by using the .NET Framework. You use the same set of classes, regardless of whether you are building an ASP.NET, Windows Forms, or console application.

The classes in the ADO.NET Framework are extremely flexible. You can use the classes in the ADO.NET Framework to connect to different types of databases, represent data by using different data access models, and work with both relational and XML data.

There are five main classes in the ADO.NET Framework:

  • ConnectionRepresents a connection to a data source

  • CommandRepresents a command that can be executed against a data source

  • DataAdapterRepresents a set of commands that can be executed against a data source

  • DataReaderRepresents a set of records using a connected model of data access

  • DataSetRepresents a set of records using a disconnected model of data access

OleDb Versus SqlClient

Most of the classes in the ADO.NET Framework have two versions. One version is designed to work with databases using OLE DB providers, and one version is designed to work specifically with Microsoft SQL Server (version 7.0 or later).

For example, there are actually two Connection classes in the ADO.NET Framework. There is an OleDbConnection class that is used for connecting to a database that has an OLE DB provider and a SqlConnection class for connecting to Microsoft SQL Server.

The OleDb classes can be used with any database that has a native OLE DB provider. Most major databases—including Microsoft Access, Oracle, and Microsoft SQL Server—have an OLE DB provider.

The SqlClient classes can be used only with Microsoft SQL Server (version 7.0 or later). These classes are optimized for SQL Server. They work directly at the network protocol layer and do not use any intermediate layers, such as OLE DB or ODBC to communicate with a database. The SqlClient classes represent the fastest database access technology that Microsoft has ever developed.

So, if you are building an application that is designed to work specifically with Microsoft SQL Server, you should use the SqlClient classes. On the other hand, if you need to communicate with another type of database or there is a possibility that you will need to work with another type of database in the future, you should use the OleDb classes.

Note

There are additional sets of ADO.NET classes for working with other types of databases or for using alternative types of connections. For example, there is a specialized set of ADO.NET classes that is designed to communicate with a database by using ODBC drivers. There’s also a set of classes designed specifically for communicating with Oracle databases.

These classes are not included with the .NET Framework by default. If you need to use these classes, you’ll need to download them from the Microsoft Web site.

DataSets Versus DataReaders

The classes in the ADO.NET Framework support two different data access models. You can use the ADO.NET classes to represent data by using a DataSet or a DataReader.

A DataSet represents an in-memory database. When you represent database data with a DataSet, you copy the data from the physical database to the in-memory database represented by a DataSet.

A DataReader, on the other hand, represents only a single record from a database at a time. When you use a DataReader, you loop through the records from the database to retrieve the records into your application.

There are two primary advantages that DataSets have over DataReaders. First, the Visual Studio .NET development environment better supports DataSets. You can use the tools provided by Visual Studio .NET to generate and work with DataSets.

Second, DataSets, unlike DataReaders, can be cached in memory. You can store a single DataSet in your server’s memory and reuse the same DataSet across multiple requests to the same or different pages. Caching data in memory can significantly improve the performance of your application.

However, DataSets also have two significant disadvantages. First, when you represent database records with a DataSet, all the records must be copied into the Web server’s memory. If you need to represent a database table with two billion records, all two billion records must be copied into memory. In contrast, because a DataReader only represents a single record at a time, you can use a DataReader to work more efficiently with large sets of records.

A second, and perhaps more important, disadvantage of DataSets is that they are significantly slower than DataReaders. If you simply need to display the contents of a database table one time, retrieving database data with a DataSet can be significantly slower than retrieving the same data with a DataReader.

Relational Versus XML Views

You can use the classes in the ADO.NET Framework to represent data by using a relational or XML model. In a relational model, data is represented as rows in a table. In an XML model, data is represented as nodes in a tree.

For example, you can copy the contents of a database table into a DataSet and represent the database data in an XML document. Alternatively, you can load the contents of an XML document into a DataSet and represent the contents of the document as rows in a table.

Creating Database Connections

Before you can do anything else with a database in your application, you need to open a connection to it. You open a database connection by using the Connection class.

There are two versions of the Connection class. You use the SqlConnection class to represent a connection to a Microsoft SQL Server (version 7.0 or later) database, and you use the OleDbConnection class to represent a connection to other types of databases, such as Microsoft Access or Oracle.

There are two ways that you can add a connection to a Web Form Page. You can create a new connection by using the Server Explorer window or by dragging the SqlConnection or OleDbConnection object from the Toolbox.

Using the Server Explorer window is the easier method of creating a connection because you can use the Server Explorer window to provide the connection information only once and create the same connection on multiple Web Form Pages.

To create add a new connection to a SQL Server database to a Web Form Page, do the following:

  1. Open the Server Explorer window by selecting Server Explorer from the View menu.

  2. In the Server Explorer window, right-click Data Connections and select Add Connection. This will open the Data Link Properties dialog box.

  3. In the Data Link Properties dialog box, select the Provider tab and select the Microsoft OLE DB Provider for SQL Server.

  4. In the Data Link Properties dialog box, select the Connection tab.

  5. Enter the name of your SQL database server. (If the database server is located on the local machine, you can enter Localhost.)

  6. Choose either Windows NT Security or SQL Server security. If you select SQL Server security by entering your username and password, make sure that you check the Allow Saving Password check box.

  7. Select a database from your database server (for example, Pubs or Northwind).

  8. Click OK to close the Data Link Properties dialog box.

  9. In the Server Explorer window, select the new connection from under Data Connections and drag the connection onto your Web Form Page.

Note

If you check the Allow Saving Password option when creating the data connection, you’ll get a warning dialog box when you finish adding the connection. Don’t let the warning scare you. You are simply being warned that your database password will be saved by Visual Studio .NET so that it can be automatically used when you add the data connection to a Web Form Page.

When you drag the connection from the Server Explorer window onto the Web Form Page, a new SqlConnection object should be added to the Designer window (see Figure 8.1).

Adding a connection with Server Explorer.

Figure 8.1. Adding a connection with Server Explorer.

The process of creating a connection to other types of databases is very similar. For example, to create a connection to a Microsoft Access database, you would choose the Microsoft JET 4.0 OLE DB Provider and provide the path to the Access database file (the .MDB file) on your hard drive.

When creating a connection to an Oracle database, you would select the Microsoft OLE DB Provider for Oracle and specify the name of the database server and login and password information.

When you create a connection to a database other than Microsoft SQL Server (version 7.0 or later), an OleDbConnection object is created instead of an SqlConnection object.

Note

Notice that we created a connection using the SqlConnection object by selecting an OLE DB provider in the Data Link Properties dialog box. This is confusing, but it’s how Visual Studio .NET works.

Using DataSets, DataAdapters, and DataViews

You can use a DataSet to represent a set of database records in your Web server’s memory. For example, you can copy the contents of a database table into a DataSet and then display the contents of the DataSet on a Web Form Page.

When you work with a DataSet, you need to work (at a minimum) with the following three objects:

  • Connection—Represents a connection to a database. When working with Microsoft SQL Server, you use the SqlConnection object and when working with other databases, you use the OleDbConnection object.

  • DataAdapter—Represents the SQL commands used to populate the DataSet with database data or update the database with changes in the DataSet.

  • DataSet—Represents a container for data

You should think of a DataSet as an in-memory database. You can add multiple DataTables to a DataSet that represent different sets of database records. Whereas a DataSet is an in-memory database, a DataTable is an in-memory database table.

A DataSet is data source agnostic. You can use a DataSet to represent records from different types of databases, such as Microsoft SQL Server and Oracle. You can also load XML files into a DataSet. You can even combine records from multiple data sources in a single DataSet. For example, you can create a DataSet that contains mixed data from an Oracle and SQL Server database and an XML file.

A DataAdapter represents the bridge between a DataSet and a physical database. You use the DataAdapter to copy records from a physical database to a DataSet. You can also use a DataAdapter to copy records back from a DataSet to a physical database.

There are two versions of the DataAdapter. The SqlDataAdapter is used to create DataSets by copying records from a Microsoft SQL Server database. The OleDbDataAdapter is used to create DataSets by copying records from other types of databases.

Displaying Database Data with a DataSet

In this section, you will learn how to add the Authors database table to a DataSet and display the contents of the DataSet with the DataGrid control.

Note

We’ll discuss the DataGrid control in detail later in this book (see Chapter 13, “Displaying Data with the DataGrid Control”). For now, we’ll just take advantage of the DataGrid as a convenient mechanism to display database records quickly.

To create and display a DataSet, you’ll need to complete each of the following tasks:

  1. Create a connection to the Pubs database.

  2. Create a DataAdapter to retrieve the data from the Authors database table.

  3. Create a DataSet that contains the Authors database table.

  4. Use the DataAdapter to fill the DataSet with records from the Authors database table.

  5. Create a DataGrid that is bound to the DataSet.

If you haven’t already created a connection to the Pubs database in the Server Explorer window, you’ll need to create one before doing anything else by doing the following:

  1. In the Server Explorer window, right-click Data Connections and select Add Connection. This will open the Data Link Properties dialog box.

  2. Select the Provider tab and select Microsoft OLE DB Provider for SQL Server.

  3. Select the Connection tab and enter the name of your database server, credential information, and select the Pubs database.

  4. Make sure that you have the Allow Saving Password check box checked.

  5. Click OK to close the Data Link Properties dialog box.

After you complete these steps, a new connection to the Pubs database is added to the Server Explorer window.

Next, you need to create the DataAdapter by performing the following steps. The DataAdapter is used to retrieve the data from the Authors database table.

  1. Add a new Web Form Page named DisplayAuthors.aspx to your project.

  2. Add an SqlDataAdapter to the Web Form Page by double-clicking the SqlDataAdapter object located under the Data tab in the Toolbox. This will launch the Data Adapter Configuration Wizard.

  3. Click Next to start the wizard.

  4. Select the connection to the Pubs database and click Next.

  5. Check the Use SQL Statements check box and click Next.

  6. Enter the statement Select * From Authors into the text box and click Next.

  7. Click Finish to close the Data Adapter Configuration Wizard.

The DataAdapter retrieves all the records from the Authors database table.

Note

If you want to create a DataAdapter that retrieves data from a database other than Microsoft SQL Server, you need to add an OleDbDataAdapter rather than an SqlDataAdapter.

Next, you need to create the DataSet and fill the DataSet with data from the Authors database table by using the DataAdapter by doing the following:

  1. Add a DataSet to the Web Form Page by double-clicking the DataSet object located under the Data tab in the Toolbox. This will open the Add Dataset dialog box.

  2. In the Add Dataset dialog box, select Untyped DataSet and click OK.

  3. Switch to the Code Editor by selecting View, Code (or double-click the Designer surface).

  4. Enter the following code for the Page_Load event handler:

    C#

    private void Page_Load(object sender, System.EventArgs e)
    {
        sqlDataAdapter1.Fill( dataSet1 );
    }
    

    VB.NET

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
    VB.NET MyBase.Load
      SqlDataAdapter1.Fill(DataSet1)
    End Sub
    

In the Page_Load event handler, the SqlDataAdapter’s Fill() method is called to fill the DataSet1 DataSet with records from the Authors table.

The final step is to display the DataSet in a DataGrid control. (The DataGrid control is discussed in detail in Chapter 13.) To do so, perform the following steps:

  1. Switch to the Designer window by selecting Designer from the View menu.

  2. Add a DataGrid control to the Web Form Page by dragging the DataGrid control located under the Web Forms tab in the Toolbox onto the Designer surface.

  3. Switch to the Code Editor by selecting Code from the View menu (or double-clicking the Designer surface).

  4. Modify the Page_Load event handler by adding the necessary code to bind the DataSet to the DataGrid. The final Page_Load subroutine should look like the following:

    C#

    private void Page_Load(object sender, System.EventArgs e)
    {
        sqlDataAdapter1.Fill( dataSet1 );
        DataGrid1.DataSource = dataSet1;
        DataGrid1.DataBind();
    }
    

    VB.NET

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
    VB.NET MyBase.Load
      SqlDataAdapter1.Fill(DataSet1)
      DataGrid1.DataSource = DataSet1
      DataGrid1.DataBind()
    End Sub
    
  5. Right-click the DisplayAuthors.aspx page in the Solution Explorer window and select Build and Browse.

When the DisplayAuthors.aspx page is opened, all the rows from the Authors database table should be displayed (see Figure 8.2). The DataGrid control displays the contents of the DataSet.

Displaying the Authors database table.

Figure 8.2. Displaying the Authors database table.

Displaying All Rows with a DataSet

In the previous section, you created a DataSet by dragging a DataAdapter from the Toolbox and completing the DataAdapter Configuration Wizard. There is an easier method of adding a DataAdapter to a page. You can simply drag a table from beneath a data connection in the Server Explorer window to create the DataAdapter automatically.

If you drag a table from Server Explorer onto the Designer surface, a DataAdapter is created that retrieves all the columns and all the rows from the table. Perform the following steps to quickly create a page that displays the contents of the Titles table.

First, you need to add the necessary objects and controls to the Web Form Page:

  1. Create a Web Form Page named ShowTitles.aspx.

  2. In the Server Explorer window, expand the Data Connection to the Pubs database.

  3. Drag the Titles table onto the Designer surface. Completing this step will automatically add a SqlConnection and SqlDataAdapter to the page.

  4. In the Toolbox, select the DataSet from under the Data tab and drag it onto the Designer surface. When the Add DataSet dialog box appears, check Untyped Dataset and click OK.

  5. In the Toolbox, select the DataGrid control from under the Web Forms tab and drag it onto the Designer surface.

Next, you need to add the code to the page to fill the DataSet and bind the DataSet to the DataGrid:

  1. Switch to the Code Editor by double-clicking the Designer surface.

  2. Enter the following code for the Page_Load() method:

    C#

    private void Page_Load(object sender, System.EventArgs e)
    {
        sqlDataAdapter1.Fill( dataSet1 );
        DataGrid1.DataSource = dataSet1;
        DataGrid1.DataBind();
    }
    

    VB.NET

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
    VB.NET MyBase.Load
        SqlDataAdapter1.Fill( DataSet1 )
        DataGrid1.DataSource = DataSet1
        DataGrid1.DataBind()
    End Sub
    
  3. Right-click the ShowTitles.aspx page in the Solution Explorer window and select Build and Browse.

After you complete these steps, the entire contents of the Titles database table will appear in the DataGrid control.

If you expand a table in the Server Explorer window, you can view the columns associated with the table. If you select one or more columns from the table and drag the columns onto the Designer surface, a DataAdapter is created that contains only those columns (and the primary key column).

Using a Typed DataSet

In the previous section, we created something called an Untyped DataSet. Instead of using an Untyped DataSet, you can use a Typed DataSet. The tables and columns contained in a DataSet are represented in different ways in a Typed and Untyped DataSet.

The tables and columns in an Untyped DataSet are represented as collections. In contrast, the tables and columns in a Typed DataSet are represented as strongly typed properties.

For example, to refer to the Authors DataTable in an Untyped DataSet, you would use the following expression:

C# Code

dataSet1.Tables("Authors")

VB.NET Code

DataSet1.Tables["Authors"]

To refer to the Authors DataTable in a Typed DataSet, in contrast, you can use the following expression:

C# Code

dataSet1.Authors

VB.NET Code

DataSet1.Authors.

One advantage of a Typed DataSet is that it supports Visual Studio .NET IntelliSense. Because tables and columns are exposed as strongly typed properties of a typed DataSet, Visual Studio .NET can display statement auto-completion options as you type.

Another advantage of Typed DataSets is that errors can be caught by Visual Studio .NET at compile time rather than runtime. If you attempt to assign the string "apple" to a decimal column in a Typed DataSet, this error can be detected when the Web Form Page is compiled.

A final advantage of Typed DataSets is better support by the Visual Studio .NET Designer. For example, when using a Typed DataSet, you can add columns to a DataGrid by name. The list of column names from the DataSet appears in the Property Pages for the DataGrid.

When you create a Typed DataSet, you add two extra objects to your project—an XML Schema and a .NET class. The XML Schema provides information about the data type of each of the columns in a DataSet. The Schema is used to generate a .NET class that derives from the DataSet class. The .NET class exposes the collections in a DataSet as strongly typed properties.

In this section, we’ll create a Typed DataSet that represents the Titles database table. We’ll display the contents of the typed DataSet in a DataGrid. The following is an overview of the steps that we’ll need to perform:

  1. Create a connection to the Pubs database.

  2. Create a DataAdapter to retrieve the data from the Titles database table.

  3. Add a Typed DataSet to the project that represents the Titles database table.

  4. Add an instance of the Typed DataSet to a Web Form Page.

  5. Use the DataAdapter to fill the instance of the Typed DataSet.

  6. Create a DataGrid that is bound to the instance of the Typed DataSet.

If you haven’t already created a connection to the Pubs database, you need to create this connection before doing anything else by doing the following:

  1. In the Server Explorer window, right-click Data Connections and select Add Connection. This will open the Data Link Properties dialog box.

  2. Select the Provider tab and select Microsoft OLE DB Provider for SQL Server.

  3. Select the Connection tab and enter the name of your database server, credential information, and select the Pubs database.

  4. Make sure that you check the Allow Saving Password check box.

  5. Click OK to close the Data Link Properties dialog box.

After you complete these steps, a new connection to the Pubs database is added to the Server Explorer window.

Next, you need to create the DataAdapter. The DataAdapter will be used for two tasks. You’ll use the DataAdapter to create the Typed DataSet and to fill the typed DataSet with records from the Titles table. To create the DataAdapter, perform the following steps:

  1. Add a new Web Form Page named ShowTypedTitles.aspx to your project.

  2. Drag the Titles table from the Pubs Data Connection onto the Designer surface. This will add both a new SqlConnection and an SqlDataAdapter object to the page.

Next, we need to generate the Typed DataSet by performing the following steps. Creating the Typed DataSet will add an XML Schema and .NET class to your project.

  1. Select Generate Dataset from the Data menu. This opens the Generate Dataset dialog box.

  2. Under Choose a Dataset, select the New radio button and enter the name TitlesDS.

  3. Make sure that the Titles table is checked and the Add This DataSet to Designer check box is checked.

  4. Click OK to generate the Typed DataSet.

When you add the Typed DataSet to your project, a new file named TitlesDS.xsd is added to your project. A .NET class file is also added to your project. To see this file, select Show All Files from the Project menu.

Because you checked the Add This DataSet to Designer check box, an instance of the typed DataSet is added automatically to your Web Form Page. The instance of the Typed DataSet added to the Web Form Page is named TitlesDS1.

Next, you need to fill the instance of the Typed DataSet with the records from the Titles database table, by doing the following:

  1. Switch to the Code Editor by selecting View, Code (or by double-clicking the Designer surface).

  2. Enter the following code for the Page_Load() method:

    C#

    private void Page_Load(object sender, System.EventArgs e)
    {
        sqlDataAdapter1.Fill(TitlesDS1);
    }
    

    VB.NET

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
    VB.NET MyBase.Load
        SqlDataAdapter1.Fill(TitlesDS1)
    End Sub
    

Finally, to display the typed DataSet in a DataGrid, you need to add a DataGrid control to the Web Form Page and bind the DataGrid to the DataSet. To do so, do the following:

  1. Switch to the Designer window by selecting Designer from the View menu.

  2. Add a DataGrid control to the Web Form Page.

  3. Switch to the Code Editor by selecting Code from the View menu (or double-click the Designer surface).

  4. Add two additional statements to the Page_Load event handler to bind the Typed DataSet to the DataGrid. The final Page_Load event handler should look like the following:

    C#

    private void Page_Load(object sender, System.EventArgs e)
    {
        sqlDataAdapter1.Fill(TitlesDS1);
        DataGrid1.DataSource = dataSet1;
        DataGrid1.DataBind();
    }
    

    VB.NET

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
    VB.NET MyBase.Load
      SqlDataAdapter1.Fill(TitlesDS1)
      DataGrid1.DataSource = DataSet1
      DataGrid1.DataBind()
    End Sub
    
  5. Right-click the ShowTypedTitles.aspx page in the Solution Explorer window and select Build and Browse.

When the ShowTypedTitles.aspx page is opened, all the rows from the Titles database table are displayed in the DataGrid control.

After you create one Typed DataSet in a project, you can add an instance of the Typed DataSet to multiple Web Form Pages in the project. For example, to add an instance of the TitlesDS Typed DataSet to another page named DisplayTypedTitles2.aspx by doing the following:

  1. Add a new Web Form Page named DisplayTypedTitles2.aspx to your project.

  2. Add a DataSet to the Web Form Page by double-clicking the DataSet object under the Data tab in the Toolbox. This will open the Add Dataset dialog box.

  3. In the Add Dataset dialog box, check the Typed DataSet radio button and select TitlesDS from the drop-down list.

  4. Click OK to close the Add Dataset dialog box.

Before you can use the instance of the Typed DataSet in the new page, you still need to fill the DataSet by using the DataAdapter. Follow the same procedure to create the DataAdapter for this new page as you did for the DisplayTitles.aspx page.

Using DataViews

A DataView provides you with a particular view of the data contained in a DataSet. You can use a DataView to represent the records in a DataSet sorted in a particular order, or you can use a DataView to represent the records in a DataSet filtered by a particular criterion (or both).

A DataView has two important properties:

  • SortThe name of the column or columns that specify the sort order of the rows in the DataView (for example, Title DESC).

  • RowFilterAn expression that filters rows in the DataView (for example, price > 10.00).

For example, suppose that you want to display a list of records from the Titles database table. However, suppose that you want to display the rows sorted by the publication date, and that you don’t want to display any book that costs less than $10.00.

Note

I want to emphasize that the example in this section is for illustrative purposes only. A better way to display the rows from the Titles table with a certain sort order and selection criteria would be to build these requirements into the original SQL Select statement that you created when building the DataAdapter. We’ll come across more realistic situations in which the DataView object can be employed on Chapter 13.

First, let’s create a new Web Form Page that contains all the necessary database objects and controls:

  1. Create a new Web Form Page named TitlesDataView.aspx.

  2. In the Server Explorer window, expand the Data Connections folder, expand the Data Connection to the Pubs database, expand the Tables folder, and drag the Titles table onto the Designer surface. Completing this step will add an SqlConnection and an SqlDataAdapter to your page.

  3. Under the Data tab in the Toolbox, drag the DataSet object onto the Web Form Page. When the Add Dataset dialog box appears, select Untyped Dataset and click OK.

  4. From the Web Forms tab in the Toolbox, drag the DataGrid control onto the Web Form Page.

Previously, we’ve bound the DataGrid directly to a DataSet. This time, however, we want to bind the DataGrid to a DataView so that we can sort and filter the contents of the DataSet by doing the following:

  • Under the Data tab in the Toolbox, drag the DataView object onto the Web Form Page.

Finally, we need to add the necessary code to the page to sort and filter the DataView and bind the DataGrid to the DataView. We do this by performing the following:

  1. Switch to the Code Editor by selecting View, Code (or double-click the Designer surface).

  2. Enter the following code for the Page_Load() handler:

    C#

    private void Page_Load(object sender, System.EventArgs e)
    {
      sqlDataAdapter1.Fill(dataSet1);
      dataView1 = dataSet1.Tables[0].DefaultView;
      dataView1.Sort = "pubdate";
      dataView1.RowFilter = "price > 10.00";
      DataGrid1.DataSource = dataView1;
      DataGrid1.DataBind();
    }
    

    VB.NET

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
    VB.NET MyBase.Load
      SqlDataAdapter1.Fill(DataSet1)
      DataView1 = DataSet1.Tables(0).DefaultView
      DataView1.Sort = "pubdate"
      DataView1.RowFilter = "price > 10.00"
      DataGrid1.DataSource = DataView1
      DataGrid1.DataBind()
    End Sub
    
  3. Right-click the page in the Solution Explorer window and select Build and Browse.

When the page opens, the titles should appear in order of the publication date. Furthermore, you shouldn’t see any book that costs less than $10.00 (see Figure 8.3).

Displaying records with a DataView.

Figure 8.3. Displaying records with a DataView.

Using DataReaders and Commands

To this point, we have examined only one set of classes included with ADO.NET for representing data. In previous sections, you learned how to use the DataSet class to represent a set of database records. However, instead of using a DataSet, you can use a DataReader.

A DataReader is about twice as fast as a DataSet. If you need to display a set of records from a database table in the quickest possible way, you should use a DataReader.

Unfortunately, the Visual Studio .NET development environment does not support DataReaders as well as it supports DataSets. This doesn’t mean that you can’t use DataReaders when building applications with Visual Studio .NET. It just means that, when working with a DataReader, you’ll need to spend more time working in the Code Editor.

Displaying Database Data with a DataReader

When representing database data with a DataReader, you need to work with the following three objects:

  • Connection—Represents a connection to a database

  • Command—Represents a database command

  • DataReader—Represents the set of records returned by the command

Like the majority of the other ADO.NET objects, there are two versions of each of these objects. There is an SQL version for working with Microsoft SQL Server (version 7.0 or later) and an OleDb version, for working with any database that has a native OLE DB Provider (all major databases including Oracle and Microsoft Access). For example, there is both a SqlDataReader and an OleDbDataReader.

Perform the following steps to add the database objects that you’ll need to create a SqlDataReader that represents the records from the Titles database table:

  1. Add a new Web Form page named TestDataReader.aspx to your project.

  2. Add an SqlConnection object to the Web Form Page by dragging a database connection from the Server Explorer window onto the Designer surface. (If you don’t have any existing connections in the Server Explorer window, see the “Creating Database Connections” section earlier in this chapter.)

  3. Add an SqlCommand object to the Web Form Page by double-clicking the SqlCommand object located under the Data tab in the Toolbox.

  4. In the Properties window, select the SqlCommand object. Assign the value SqlConnection1 to the Connection property and assign the text Select * From Titles to the CommandText property.

  5. Modifying the CommandText property will cause a dialog box to appear asking you whether you want to regenerate the parameters collection for the command. Click No.

Next, we can create the SqlDataReader in the Code Editor by doing the following:

  1. Switch to the Code Editor by selecting View, Code (or by double-clicking the Designer surface).

  2. Enter the following code for the Page_Load() handler:

    C#

    private void Page_Load(object sender, System.EventArgs e)
    {
      System.Data.SqlClient.SqlDataReader dtrTitles;
      sqlConnection1.Open();
      dtrTitles = sqlCommand1.ExecuteReader();
      sqlConnection1.Close();
    }
    

    VB.NET

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
    VB.NET MyBase.Load
      Dim dtrTitles As System.Data.SqlClient.SqlDataReader
      SqlConnection1.Open()
      dtrTitles = SqlCommand1.ExecuteReader()
      SqlConnection1.Close()
    End Sub
    

The Page_Load() handler creates a SqlDataReader by calling the ExecuteReader() method of the SqlCommand object. Notice that the database connection, represented by the SqlConnection object, must be explicitly opened before the ExecuteReader method is called.

To test our SqlDataReader, we’ll display its contents in a DataGrid control. (The DataGrid control is covered in detail in Chapter 13.) First we add the DataGrid:

  1. Switch back to the Designer by selecting Designer from the View menu.

  2. Add a DataGrid control to the TestDataReader.aspx page by dragging the control from the Toolbox onto the Designer surface.

Next, we can bind the DataGrid to the DataReader:

  1. Switch to the Code Editor by selecting View, Code (or by double-clicking the Designer surface).

  2. Modify the Page_Load() method so that it contains the following code:

    C#

    private void Page_Load(object sender, System.EventArgs e)
    {
      System.Data.SqlClient.SqlDataReader dtrTitles;
      sqlConnection1.Open();
      dtrTitles = sqlCommand1.ExecuteReader();
      DataGrid1.DataSource = dtrTitles;
      DataGrid1.DataBind();
      sqlConnection1.Close();
    }
    

    VB.NET

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
    VB.NET MyBase.Load
      Dim dtrTitles As System.Data.SqlClient.SqlDataReader
      SqlConnection1.Open()
      dtrTitles = SqlCommand1.ExecuteReader()
      DataGrid1.DataSource = dtrTitles
      DataGrid1.DataBind()
      SqlConnection1.Close()
    End Sub
    
  3. In the Solution Explorer window, right-click the TestDataReader.aspx page and select Build and Browse.

The additional statements in the Page_Load() handler copy the contents of the SqlDataReader into the DataGrid control. When the page is opened, all the records from the Titles database table are displayed in the DataGrid control (see Figure 8.4).

Displaying records with a DataReader.

Figure 8.4. Displaying records with a DataReader.

Caching Data for Better Performance

Accessing a database is one of the slowest operations that you can perform in a Web application. Whenever possible, you should avoid opening a connection to a database and retrieving records. One good way to avoid accessing a database is to cache database data in your server’s memory. Although access to the data in a database is slow, access to data in memory is lightning fast.

In this section, you’ll learn how to take advantage of the Cache object to store a DataSet in memory so that you can use the same DataSet across multiple page requests.

Using the Cache Object

If you add an item to the Cache object in a Web Form Page, the item remains in the cache across multiple page requests. By taking advantage of the Cache object, you need to retrieve a set of records from the database only once.

For example, suppose that you are building an online store that sells a couple thousand products. You could load the list of products into a DataSet and store the DataSet in the Cache. That way, whenever someone wants to view a list of products, the list of products can be quickly retrieved from memory instead of from the database.

Because you can sort and filter records in a DataSet, by using the DataView object, you can even present different views of the items in the Cache. For example, you can display all the products related to Beanie Babies on one page and display all the products related to TeleTubbies on another.

The Cache object has two important methods:

  • InsertInserts a new item into the Cache

  • RemoveRemoves an item from the Cache

For example, you would use the following code to add the string Hello World! to the Cache object:

C# Code

Cache.Insert( "myString", "Hello World!" );

VB.NET Code

Cache.Insert( "myString", "Hello World!" )

This statement adds a new item to the cache named myString that has the value Hello World!. You can abbreviate the previous Insert statement as follows:

C# Code

Cache[ "myString" ] = "Hello World!";

VB.NET Code

Cache( "myString" ) = "Hello World!"

You would use the following statement to remove the myString item from the Cache:

C# Code

Cache.Remove( "myString" );

VB.NET Code

Cache.Remove( "myString" )

There are two important warnings that you must heed that concern the Cache object. First, the Cache object is case sensitive (even in VB.NET). Consequently, adding an item named Item1 to the Cache is different than adding an item named ITEM1.

Second, items that you add to the Cache are not guaranteed to be there when you attempt to retrieve them. The Cache object automatically drops items from the cache when your Web server’s memory gets too low.

For this reason, you should always check to make sure that an item still exists after you retrieve it from the Cache. You can check whether something exists by comparing it to the value null when using C# or the keyword Nothing when using Visual Basic .NET.

Typically, when you want to retrieve an item from the Cache, you use logic that looks like the following:

C# Code

string strMessage = "";

strMessage = (string)Cache["message"];
if (strMessage == null)
{
  strMessage = "Hello World!";
  Cache["message"] = strMessage;
}
Response.Write(strMessage);

VB.NET Code

Dim strMessage As String
strMessage = Cache("message")
If strMessage = Nothing Then
  strMessage = "Hello World!"
  Cache("message") = strMessage
End If
Response.Write(strMessage)

In this example, an item named message is stored in the Cache. After the item is retrieved from the Cache, the item is compared against either null or Nothing. If the item doesn’t have a value, the item is recreated and added to the Cache. In either case, the value of the item is displayed.

In this case, we added a string to the Cache. However, you’ll use the same logic with any item, such as a DataSet, that you might add to the Cache.

Caching a DataSet in Memory

In this section, you will learn how to store the Products database table in the Cache object. You will load the Products database into a DataSet and add the DataSet to the Cache.

You’ll create a page that displays the cached Products table in a DataGrid. To create this page, you’ll need to complete the following steps:

  1. Create a connection to the Northwind database.

  2. Create a DataSet that represents the Products database table.

  3. Cache the contents of the DataSet in the Cache object.

  4. Create a DataGrid that is bound to the cached DataSet.

The first step is to create the connection to the Northwind database. The Northwind database is a sample database that is automatically created when you install SQL Server. Perform the following steps to create the connection:

  1. In the Server Explorer window, right-click Data Connections and select Add Connection. This will open the Data Link Properties dialog box.

  2. Select the Provider tab and select Microsoft OLE DB Provider for SQL Server.

  3. Select the Connection tab and enter the name of your database server, credential information, and select the Northwind database.

  4. Make sure that you check the Allow Saving Password check box.

  5. Click OK to close the Data Link Properties dialog box.

Completing these steps will add a new connection to the Server Explorer window.

Next, we need to create a new Web Form Page and add the necessary database objects and controls to the page by doing the following:

  1. Create a new Web Form Page named CachedProducts.aspx.

  2. In the Server Explorer window, expand the Data Connection to the Northwind database and expand the Tables folder. Drag the Products database table onto the Designer surface.

  3. Under the Data tab in the Toolbox, find the DataSet object and drag it onto the Designer surface. When the Add Dataset dialog box appears, select Untyped DataSet and click OK.

  4. Under the Web Forms tab in the Toolbox, find the DataGrid control and drag it onto the Designer surface.

  5. Under the Web Forms tab in the Toolbox, find the Label control and drag it onto the Designer surface.

Finally, we need to fill the DataSet with data from the Products database table by using the DataAdapter, add the DataSet to the Cache, and display the cached data in a DataGrid.

  1. Switch to the Code Editor by selecting View, Code (or by double-clicking the Designer surface).

  2. Modify the Page_Load() method so that it contains the following code:

    C#

    private void Page_Load(object sender, System.EventArgs e)
    {
      dataSet1 = (DataSet)Cache[ "Products" ];
      if (dataSet1 == null)
      {
        Label1.Text = "Retrieving data from database!";
        dataSet1 = new DataSet();
        sqlDataAdapter1.Fill( dataSet1 );
        Cache[ "Products" ] = dataSet1;
      }
      DataGrid1.DataSource = dataSet1;
      DataGrid1.DataBind();
    }
    

    VB.NET

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
    VB.NET MyBase.Load
      DataSet1 = Cache("Products")
      If DataSet1 Is Nothing Then
        Label1.Text = "Retrieving data from database!"
        DataSet1 = New DataSet()
        SqlDataAdapter1.Fill(DataSet1)
        Cache("Products") = DataSet1
      End If
      DataGrid1.DataSource = DataSet1
      DataGrid1.DataBind()
    End Sub
    
  3. In the Solution Explorer window, right-click the CachedProducts.aspx page and select Build and Browse.

The first time you open the CachedProducts.aspx page, the Products database table will be retrieved from the database and the message “Retrieving data from database!” will appear in the Label control (see Figure 8.5). However, if you refresh the page (by selecting Refresh from the View menu), the Products table will be retrieved from the Cache object instead of the database.

Displaying cached records.

Figure 8.5. Displaying cached records.

Summary

In this chapter, you were introduced to the most important classes for working with database data. In the first part of this chapter, you learned how to work with both Untyped and Typed DataSets to represent and display database data. You learned how to take advantage of DataAdapters to copy a set of records into a DataSet.

Next, you learned an alternative, and faster, method of representing database data with a DataReader. You used a Command object with a DataReader to quickly retrieve and display records from a database table.

Finally, you discovered how to improve the performance of database access in a Web Form Page by using the Cache object. You used the Cache object to store a DataSet in the Web server’s memory so that the same cached data can be used across multiple page requests.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset