The goal of ADO.NET is to provide a bridge between your objects in ASP.NET and your back-end database. ADO.NET provides an object-oriented view into the database, encapsulating many of the database properties and relationships within ADO.NET objects. Further, and in many ways most important, the ADO.NET objects encapsulate and hide the details of database access; your objects can interact with ADO.NET objects without you knowing or worrying about the details of how the data is moved to and from the database.
An overview of the ADO.NET architecture is shown in Figure 10-1. We will return to the aspects of this figure throughout the chapter.
The ADO.NET object model is rich, but at its heart, it is a fairly straightforward set of classes. The key class is the DataSet , which is located in the System.Data namespace (shown in the upper right-hand corner of Figure 10-1).
The dataset represents a rich subset of the entire database, cached in session state or in memory, without a continuous connection to the database. Periodically, you'll reconnect the dataset to its parent database, which is how you update the database with changes to the dataset you've made, and update the dataset with changes in the database made by other processes.
The dataset doesn't just capture a few rows from a single table but represents a set of tables with all the metadata necessary to represent the relationships and constraints among the tables recorded in the original database, as shown in Figure 10-2.
The dataset consists of DataTable objects as well as DataRelation objects. These are accessed as the Tables and Relations properties, respectively, of the DataSet object. The most important methods and properties of the DataSet class are shown in Tables 10-1 and 10-2.
Property name | Type | Get | Set | Description |
---|---|---|---|---|
DefaultViewManager | DataViewManager |
| Returns a view of the data in the DataSet that allows filtering, searching, and navigation. | |
HasErrors | BooleanBoolen |
| Returns true if there are any errors in any of the rows of any of the tables. | |
Relations | DataRelationCollection |
| Returns a collection of DataRelation objects. | |
Tables | DataTableCollection |
| Returns a collection of DataTable objects. |
Method name | Return type | Description |
---|---|---|
AcceptChanges | void | Accepts all the changes made since loaded or since last time AcceptChanges was called (see GetChanges ). |
Clear | void | Clears the dataset of any data. |
GetChanges | DataSet | Returns a copy of the dataset containing all the changes made since loaded or since AcceptChanges was called. |
GetXML | string | Returns the XML representation of the data in the dataset. |
GetXMLSchema | string | Returns the XSD schema for the XML representation of the data in the dataset. |
Merge | void | Merges the data in this dataset with another dataset. Overloaded. |
ReadXML | XmlReadMode | Reads an XML schema and data into the dataset. Overloaded. |
ReadXMLSchema | void | Reads an XML schema into the dataset. |
RejectChanges | void | Rolls back to the state since last AcceptChanges (see AcceptChanges ). |
WriteXML | void | Writes out the XML schema and data from the dataset. Overloaded. |
WriteXMLSchema | void | Writes the structure of the dataset as an XML schema. Overloaded. |
The DataRelation class contains a DataRelationCollection object, which contains DataRelation objects. Each DataRelation object represents a relationship between two tables through DataColumn objects. For example, in the Northwind database, the Orders table is in a relationship with the Customers table through the CustomerID column. The nature of this relationship is parent/child: for any given Order, there will be exactly one customer, but any given customer may be represented in any number of Orders.
The DataSet object's Tables property returns a DataTableCollection collection, which in turn contains all the DataTable objects in the dataset. For example, the following line of code creates a reference to the first DataTable in the Tables collection of a DataSet object named myDataSet .
DataTable dataTable = myDataSet.Tables[0];
The DataTable has a number of public properties, including the Columns property, which returns the ColumnsCollection object, which in turn consists of DataColumn objects. Each DataColumn object represents a column in a table.
The most important properties and methods of the DataTable class are shown in Tables 10-3 and 10-4.
Property name | Type | Get | Set | Description |
---|---|---|---|---|
ChildRelations | DataRelationCollection - DataRelationCollection |
| Returns the collection of child relations (see Relations object). | |
Columns | DataColumnCollection |
| Returns the columns collection. | |
Constraints | ConstraintCollection |
| Returns the constraints collection. | |
DataSet | DataSet |
| Returns the dataset this table belongs to. | |
DefaultView | DataView |
| Returns a view of the table for filtering. | |
ParentRelations | DataRelationCollection |
| Returns the parent relations collection. | |
PrimaryKey | DataColumn |
|
| An array of columns as primary key for this table. |
Rows | DataRowCollection |
| Returns the rows collection. |
Method name | Return type | Description |
---|---|---|
AcceptChanges | void | Commits all the changes since last AcceptChanges . |
Clear | void | Clears the table of all data. |
GetChanges | DataTable | Returns a copy of the DataTable that contains all the changes since last AcceptChanges (see AcceptChanges ). |
GetErrors | DataRow[] | Returns an array of rows with errors. |
ImportRow | void | Copies a row into a table, including all settings and values. |
LoadDataRow | DataRow | Finds and updates a specific row. Creates a new row if no matching row is found. Overloaded. |
Merge | void | Merges the specified DataTable with the current DataTable . Overloaded. |
NewRow | DataRow | Creates a new DataRow with the same schema as the table. |
RejectChanges | void | Rolls back changes since last AcceptChanges (see AcceptChanges ). |
Reset | void | Resets the table to its original state. |
Select | DataRow[] | Returns an array of DataRow objects. Overloaded. |
|
The Rows collection returns a set of rows for any given table. You use this collection to examine the results of queries against the database, iterating through the rows to examine each record in turn.
|
The most important methods and properties of the DataRow class are shown in Tables 10-5 and 10-6.
Name | Type | Get | Set | Description |
---|---|---|---|---|
HasErrors | Boolean |
| Returns true if the row has any errors. | |
Item | object |
|
| Gets or sets the data stored in a specific column (in C#, this is the indexer). |
ItemArray | object |
|
| Gets or sets all the values for the row using an array. |
Table | DataTable |
| Gets the table this row is owned by. |
Name | Return type | Description |
---|---|---|
AcceptChanges | voidVoid | Accepts all the changes since the last time AcceptChanges was called. |
BeginEdit | voidVoid | Begins an edit operation. |
CancelEdit | voidVoid | Cancels the edit operation. |
Delete | voidVoid | Deletes the DataRow from the DataTable . |
EndEdit | voidVoid | Ends the edit operation. |
GetChildRows | DataRows[] | Gets the child rows for this row. Overloaded. |
GetParentRow | DataRow | Gets the parent row of this row. Overloaded. |
GetParentRows | DataRow[] | Gets parent rows of a DataRow . Overloaded. |
RejectChanges | voidVoid | Rejects all the changes since the last time AcceptChanges was called (see AcceptChanges ). |
The DbConnection object represents a connection to a data source. This connection may be shared among different command objects and is used in support of transactions (explained later in this chapter).
The DbCommand object allows you to send a command (typically an SQL statement or the name of a stored procedure) to the database. Often DbCommand objects are implicitly created when you create your dataset, but you can explicitly access these objects as you'll see in a subsequent example.
Rather than tie the DataSet object too closely to your database architecture, ADO.NET uses a DataAdapter object to mediate between the DataSet object and the database. This decouples the dataset from the database and allows a single dataset to represent more than one database or other data source.
ASP.NET provides different versions of the DataAdapter object. For example, there is one for use with SQL Server, and another for use with OLE DB providers such as Access. If you are connecting to a SQL Server database (or SQLExpress ), you will increase the performance of your application by using SqlDataAdapter (from System.Data.SqlClient ) along with SqlCommand and SqlConnection .
|
The DataAdapter class provides several properties, such as AcceptChangesDuringFill , AcceptChangesDuringUpdate , and ContinueUpdateOnError , to control the behavior of the object. It has a number of useful methods; the three most important are listed in Table 10-7.
Name | Return type | Description |
---|---|---|
Fill | integer | Fills a DataTable by adding or updating rows in the dataset. The return value is the number of rows successfully added or updated. Overloaded. |
FillSchema | DataTable[] | Adds a DataTable object to the specified dataset. Configures the schema (the logical design of the database) to the specified SchemaType . It returns a DataTable object containing the schema data. |
Update | integer | Updates all the modified rows in the specified table of the DataSet . Returns the number of rows successfully updated. |
An alternative to the dataset is the DataReader object. The DataReader provides database-connected forward-only access to a record set records executing a SQL statement or a stored procedure. DataReaders are lightweight objects ideally suited for filling a web page with read-only data, such as populating lists, and then breaking the connection to the back-end database.
The base class for all DataReaders is DbDataReader in the System.Data.Common namespace.
The classes derived from DbDataReader are DataTableReader , OdbcDataReader , OleDbDa-taReader , OracleDataReader , SqlDataReader , and SqlCeDataReader .
The DbDataReader class has properties such as FieldCount and HasRows for obtaining information about the data. Of particular interest is the Item property, which returns an object representing the value of a specified column in the row. In C#, the item property is the indexer for the class.
The DbDataReader class has a large number of methods for extracting the data as you iterate through the reader, such as GetBytes , GeTData , GetName , and GetString . Other important methods are listed in Table 10-8.
Name | Return type | Description |
---|---|---|
Close | void | Closes the data reader. Overridden. |
Nextresult | Boolean | When reading the results of a batch SQL statement, advances to the next result set (set of records). Will return TRue if there are more result sets. Overridden. |
Read | Boolean | Advances to the next record. Will return true if there are more records. |
The DataReader is a powerful object, but you don't often use many of its methods or properties. Most of the time, you use the DataReader to retrieve and iterate through the records that represent the result of your query.