Section 10.1. The ADO.NET Object Model

10.1. The ADO.NET Object Model

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.

Figure 10-1. ADO.NET architecture diagram

10.1.1. The DataSet Class

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.

Figure 10-2. Dataset

Table 10-1. Important DataSet properties (all read-only)

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.


Table 10-2. Important DataSet methods

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.

10.1.1.1. The DataTable class

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.

Table 10-3. Important DataTable properties

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.


Table 10-4. Important DataTable methods

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 DataTable DefaultView returns an object of type DataView , which can be used for data binding to controls such as the GridView .


10.1.1.2. The DataRow class

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.

Programmers experienced with classic ADO may be confused by the absence of the RecordSet , with its moveNext and movePrevious commands. With ADO.NET, you do not iterate through the dataset; instead you access the table you need, and then you can iterate through the rows collection, typically with a foreach loop. You'll see this in the first example in this chapter.


The most important methods and properties of the DataRow class are shown in Tables 10-5 and 10-6.

Table 10-5. Important DataRow properties

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.


Table 10-6. Important DataRow methods

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 ).


10.1.2. DbCommand and DbConnection

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.

10.1.3. The DataAdapter Object

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 .

There are two ways programmers pronounce the letters "SQL." One is Ess-Queue-Ell, the other (preferred by many of the cognoscente) is "SEE-Quill." Thus, in this book we will write " a SQL query," which is to be read "a see-quill query".


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.

Table 10-7. Important DataAdapter methods

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.


10.1.4. The Data Reader Object

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.

Table 10-8. Important DbDataReader methods

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.



Programming ASP. NET
Programming ASP.NET 3.5
ISBN: 0596529562
EAN: 2147483647
Year: 2003
Pages: 173

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net