An application uses three basic objects to move data to and from a database: a connection, a data adapter, and a data container such as a DataSet. The connection object defines the connection to the database. It contains information about the database’s name and location, any user name and password needed to access the data, database engine information, and flags that determine the kinds of access the program will need.
The data adapter object defines a mapping from the database to the DataSet. It determines what data is selected from the database, and which database columns are mapped to which DataSet columns.
The DataSet object stores the data within the application. It can hold more than one table and can define and enforce relationships among the tables. For example, the database used in the earlier examples in this chapter has a TestScores table that has a StudentId field. The values in this field must be values listed in the Students table. This is called a foreign key constraint. The DataSet can represent this constraint and raise an error if the program tries to create a TestScores record with a StudentId value that does not appear in the Students table.
When the connection, data adapter, and DataSet objects are initialized, the program can call the data adapter’s Fill method to copy data from the database into the DataSet. Later it can call the data adapter’s Update method to copy any changes to the data from the DataSet back into the database. Figure 11-19 shows the process.
Figure 11-19: An application uses connection, data adapter, and DataSet objects to move data to and from the database.
If you compare Figure 11-19 to Figure 11-18, you’ll see several similarities. Both approaches use an adapter to copy data between the database and a DataSet. At first glance, it may seem that Figure 11-18 doesn’t use a connection object, but actually the TableAdapter contains a connection object internally that it uses to access the database.
One major difference is that Figure 11-18 uses a BindingSource to provide an extra layer between the DataSet and the program’s controls. It also includes a DataNavigator object that lets the user control the BindingSource to move through the data.
As in the previous example, a program using the objects shown in Figure 11-19 could call the data adapter’s Fill method in a form’s Load event handler. Later it could call the Update method when the user clicked a Save button, in the form’s FormClosing event handler, or whenever you wanted to save the data.