CHAPTER 22 ADO.NET PART II: THE DISCONNECTED LAYER
Main() method as follows (you might need to change the connection string, based on how you created
the AutoLot database in Chapter 21):
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Data Adapters *****\n");
// Hard-coded connection string.
string cnStr = "Integrated Security = SSPI;Initial Catalog=AutoLot;" +
@"Data Source=(local)\SQLEXPRESS";
// Caller creates the DataSet object.
DataSet ds = new DataSet("AutoLot");
// Inform adapter of the Select command text and connection string.
SqlDataAdapter dAdapt =
new SqlDataAdapter("Select * From Inventory", cnStr);
// Fill our DataSet with a new table, named Inventory.
dAdapt.Fill(ds, "Inventory");
}
// Display contents of DataSet using
// helper method created earlier in this chapter.
PrintDataSet(ds);
Console.ReadLine();
Notice that you construct the data adapter by specifying a string literal that will map to the SQL
SELECT statement. You will use this value to build a command object internally, which you can obtain
later using the SelectCommand property.
Next, notice that it is the job of the caller to create an instance of the DataSet type, which is passed
into the Fill() method. Optionally, you can pass the Fill() method as a second argument a string
name that you use to set the TableName property of the new DataTable (if you do not specify a table name,
the data adapter will simply name the table, Table). In most cases, the name you assign a DataTable will
be identical to the name of the physical table in the relational database; however, this is not required.
Note The Fill() method returns an integer that represents the number of rows returned by the SQL query.
Finally, notice that you do not explicitly open or close the connection to the database anywhere in
the Main() method. You preprogram the Fill() method of a given data adapter to open and then close
the underlying connection before returning from the Fill() method. Therefore, when you pass the
DataSet to the PrintDataSet() method (implemented earlier in this chapter), you are operating on a
local copy of disconnected data, incurring no round trips to fetch the data.
Mapping Database Names to Friendly Names
As mentioned previously, database administrators tend to create table and column names that are less
than friendly to end users (e.g., au_id, au_fname, or au_lname). The good news is that data adapter objects
890