Training
Certifications
Books
Special Offers
Community




 
Programming Microsoft® Visual Basic® .NET (Core Reference)
Author Francesco Balena (Wintellect)
Pages 1616
Disk 1 Companion CD(s)
Level All Levels
Published 04/17/2002
ISBN 9780735613751
Price $59.99
To see this book's discounted price, select a reseller below.
 

More Information

About the Book
Table of Contents
Sample Chapter
Index
Companion Content
Related Series
Related Books
About the Author

Support: Book & CD

Rate this book
Barnes Noble Amazon Quantum Books

 


Chapter 21: ADO.NET in Disconnected Mode



21   ADO.NET in Disconnected Mode

In the preceding chapter, you saw how to work with ADO.NET in connected mode, processing data coming from an active connection and sending SQL commands to one. ADO.NET in connected mode behaves much like classic ADO, even though the names of the involved properties and methods (and their syntax) are often different.

You see how ADO.NET differs from its predecessor when you start working in disconnected mode. ADO 2.x permits you to work in disconnected mode using client-side static recordsets opened in optimistic batch update mode. This was one of the great new features of ADO that has proved to be a winner in client/server applications of any size. As a matter of fact, working in disconnected mode is the most scalable technique you can adopt because it takes resources on the client (instead of on the server) and, above all, it doesn't enforce any locks on database tables (except for the short-lived locks that are created during the update operation).

The DataSet Object

Because ADO.NET (and .NET in general) is all about scalability and performance, the disconnected mode is the preferred way to code client/server applications. Instead of a simple disconnected recordset, ADO.NET gives you the DataSet object, which is much like a small relational database held in memory on the client. As such, it provides you with the ability to create multiple tables, fill them with data coming from different sources, enforce relationships between pairs of tables, and more.

Even with all its great features, however, the DataSet isn't always the best answer to all database programming problems. For example, the DataSet object is great for traditional client/server applications—for example, a Windows Forms application that queries a database on a networked server—but is almost always a bad choice in ASP.NET applications and, more generally, in all stateless environments. An ASP.NET page lives only a short lifetime, just for the time necessary to reply to a browser's request, so it rarely makes sense to use a DataSet to read data from a database, then send the data to the user through HTML, and destroy the DataSet immediately afterward. (Yes, you might save the DataSet in a Session variable, but this technique takes memory on the server and might create server affinity, two problems that impede scalability, as I explain in the "State Management and Caching" section of Chapter 24.)

Exploring the DataSet Object Model

The DataSet is the root and the most important object in the object hierarchy that includes almost all the objects in the System.Data namespace. Figure 21-1 shows the most important classes in this hierarchy, with the name of the property that returns each object.

An important feature of the DataSet class is its ability to define relationships between its DataTable objects, much like what you do in a real database. For example, you can create a relationship between the Publishers and the Titles DataTable objects by using the PubId DataColumn that they have in common. After you define a DataRelation object, you can navigate from one table to another, using the DataTable's ChildRelations and ParentRelations properties.

A DataSet object consists of one or more DataTable objects, each one containing data coming from a database query, an XML stream, or code added programmatically. Table 21-1 summarizes the most important members of the DataSet class.

Click to view graphic
Click to view graphic

Figure 21-1.The DataSet object hierarchy.

Table 21-1 Main Properties, Methods, and Events of the DataSet Class

CategoryNameDescription
PropertiesDataSetNameThe name of this DataSet object.
 NamespaceThe namespace for this DataSet, used when importing or exporting XML data.
 PrefixThe XML prefix for the DataSet namespace.
 CaseSensitiveTrue if string comparisons in this DataSet are case sensitive.
 LocaleThe CultureInfo object containing the locale information used to compare strings in the DataSet (read/write).
 HasErrorsReturns True if there are errors in any of the DataTable objects in this DataSet.
 EnforceConstraintsTrue if constraint rules are enforced when attempting an update operation.
 TablesReturns the collection of child DataTable objects.
 RelationsReturns the collection of DataRelation objects.
 ExtendedPropertiesReturns the PropertyCollection object used to store custom information about the DataSet.
 DefaultViewManagerReturns a DataViewManager object that allows you to create custom search and filter settings for the DataTable objects in the DataSet.
MethodsAcceptChangesCommits all changes to this DataSet after it was loaded or since the most recent AcceptChanges method.
 RejectChangesRejects all changes to this DataSet after it was loaded or since the most recent AcceptChanges method.
 HasChangesReturns True if the DataSet has changed. It takes an optional DataRowState argument that lets you check for modified, inserted, or deleted rows only.
 MergeMerges the current DataSet with another DataSet, a DataTable, or a DataRow array.
 ResetResets the DataSet to its original state.
 CloneCreates a cloned DataSet that contains the identical structure, tables, and relationships as the current one.
 CopyCreates a DataSet that has both the same structure and the same data as the current one.
 ClearClears all the data in the DataSet.
 GetChangesGets a DataSet that contains all the changes made to the current one since it was loaded or since the most recent AcceptChanges method, optionally filtered using the DataRowState argument.
 ReadXmlReads an XML schema and data into the DataSet.
 ReadXmlSchemaReads an XML schema into the DataSet.
 GetXmlReturns the XML representation of the contents of the DataSet.
 InferXmlSchemaInfers the XML schema from the TextReader or from the file into the DataSet.
 WriteXmlWrites the XML schema and data from the current DataSet.
 WriteXmlSchemaWrites the current DataSet's structure as an XML schema.
EventsMergeFailedFires when two DataSet objects being merged have the same primary key value and the EnforceConstraints property is True.

In the remainder of this section, I'll briefly introduce all the major classes in the DataSet hierarchy, with a list of their most important properties, methods, and events. Once you have an idea of the purpose of each object, I'll describe how to perform the most common operations in disconnected mode.

The DataTable Class

A DataTable object resembles a database table and has a collection of DataColumn instances (the fields) and DataRow instances (the records). It can also have a primary key based on one or more columns and a collection of Constraint objects, which are useful for enforcing the uniqueness of the values in a column. DataTable objects in a DataSet class are often tied to each other through relationships, exactly as if they were database tables. A DataTable object can also exist outside a DataSet class, the main limitation being that it can't participate in any relationships.

Table 21-2 summarizes the most important members of the DataTable object. As you see, some of the properties and methods have the same names and meaning as properties and methods in the DataSet class.

Table 21-2 Main Properties, Methods, and Events of the DataTable Class

CategoryNameDescription
PropertiesTableNameThe name of this DataTable object.
 NamespaceThe namespace for this DataTable, used when importing or exporting XML data.
 PrefixThe XML prefix for the DataTable namespace.
 CaseSensitiveReturns True if string comparisons in this DataTable are case sensitive.
 LocaleThe CultureInfo object containing the locale information used to compare strings in the DataTable (read/write).
 HasErrorsReturns True if there are errors in any of the DataRow objects in this DataTable.
 DataSetReturns the DataSet this DataTable belongs to.
 RowsReturns the collection of child DataRow objects.
 ColumnsReturns the collection of child DataColumn objects.
 ChildRelationsReturns the collection of DataRelation objects in which this DataTable is the master table.
 ParentRelationsReturns the collection of DataRelation objects in which this DataTable is the detail table.
 ConstraintsReturns the collection of the Constraint objects for this DataTable (for example, foreign key constraints or unique constraints).
 ExtendedPropertiesReturns the PropertyCollection object used to store custom information about the DataTable.
 MinimumCapacityThe initial number of rows for this DataTable (read/write).
 PrimaryKeyAn array of DataColumn objects that represent the primary keys for the DataTable.
 DefaultViewReturns the DataView object that you can use to filter and sort this DataTable.
 DisplayExpressionA string expression used to represent this table in the user interface. The expression supports the same syntax defined for the DataColumn's Expression property.
MethodsAcceptChangesCommits all changes to this DataTable after it was loaded or since the most recent AcceptChanges method.
 RejectChangesRejects all changes to this DataTable after it was loaded or since the most recent AcceptChanges method.
 ResetResets the DataTable to its original state.
 CloneCreates a cloned DataTable that contains the identical structure, tables, and relationships as the current one.
 CopyCreates a DataTable that has both the same structure and the same data as the current one.
 ClearClears all the data in the DataTable.
 GetChangesGets a DataTable that contains all the changes made to the current one after it was loaded or since the most recent AcceptChanges method, optionally filtered by the DataRowState argument.
 NewRowCreates a DataRow with the same schema as the current table.
 ImportRowCopies the DataRow passed as an argument into the current table. The row retains its original and current values, its DataRowState values, and its errors.
 SelectReturns the array of all the DataRow objects that satisfy the filter expression. It takes optional arguments that specify the desired sort order and the DataViewRowState to be matched.
 GetErrorsReturns the array of all the DataRow objects that have errors.
 ComputeCalculates the expression specified by the first argument for all the rows that satisfy the filter expression specified in the second argument.
 BeginLoadDataTurns off notifications, index maintenance, and constraints while loading data; to be used in conjunction with the EndLoadData and LoadDataRow methods.
 EndLoadDataEnds a load data operation started with BeginLoadData.
 LoadDataRowFinds and updates a specific row or creates a new row if no matching row is found.
EventsColumnChangingFires when a DataColumn is changing. The event handler can inspect the new value.
 ColumnChangedFires after a DataColumn has changed.
 RowChangingFires when a DataRow is changing.
 RowChangedFires after a DataRow has changed.
 RowDeletingFires when a DataRow is being deleted.
 RowDeletedFires after a DataRow has been deleted.

The DataRow Class

The DataRow class represents an individual row (or record) in a DataTable. Each DataRow contains one or more fields, which can be accessed through its Item property. (Because it's the the default member, the name of this property can be omitted.) Table 21-3 lists the main properties and methods of the DataRow object.

Table 21-3 Main Properties and Methods of the DataRow Class

CategoryNameDescription
PropertiesItemGets or sets the data stored in the specified column. The argument can be the column name, the column index, or a DataColumn object. An optional DataRowVersion argument lets you retrieve the current, original, proposed, or default value for the column.
 ItemArrayGets or sets the values of all the columns, using an Object array.
 RowStateThe current state of this row; can be Unchanged, Modified, Added, Deleted, or Detached.
 HasErrorsReturns True if there are errors in the column collection.
 RowErrorGets or sets a string containing the custom error description for the current row.
MethodsAcceptChangesCommits all changes to this DataRow after it was loaded or since the most recent AcceptChanges method.
 RejectChangesRejects all changes to this DataRow after it was loaded or since the most recent AcceptChanges method.
 BeginEditMarks the beginning of an edit operation on a DataRow.
 EndEditConfirms all the changes to the DataRow since the most recent BeginEdit method.
 CancelEditCancels all the changes to the DataRow since the most recent BeginEdit method.
 DeleteDeletes this row.
 GetColumnErrorReturns the error description for the error in the column specified by the argument, which can be the column name, the column index, or a DataColumn object.
 GetColumnsInErrorReturns the array of DataColumn objects that have an error.
 SetColumnErrorSets an error description for the specified column.
 ClearErrorsClear all errors for this row, including the RowError property and errors set with the SetColumnError method.
 IsNullReturns True if the specified column has a null value. The argument can be a column name, a column index, or a DataColumn. An optional second argument lets you refer to a specific DataRowVersion value (original, current, etc.).
 GetChildRowsReturns an array of the DataRow objects that are the child rows of the current row, following the relationship specified by the argument, which can be a relationship name or a DataRelation object. An optional second argument lets you refer to a specific DataRowVersion (original, current, etc.) for the row to be retrieved.
 GetParentRowReturns the parent DataRow object, following the relationship specified by the argument (which can be one of the values accepted by the GetChildRows method).
 GetParentRowsReturns an array of the parent DataRow objects, following the relationship specified by the argument (which can be one of the values accepted by the GetChildRows method).
 SetParentRowSets the parent DataRow for the current row.

The DataColumn Class

The DataColumn class represents a single column (field) in a DataRow or in a DataTable. Not counting the methods inherited from System.Object, this class exposes only the properties summarized in Table 21-4. All properties are read/write except where otherwise stated.

Table 21-4 Main Properties of the DataColumn Class

NameDescription
ColumnNameThe name of this column.
DataTypeThe System.Type object that defines the data type of this column.
MaxLengthThe maximum length of a text column.
AllowDBNullA Boolean that determines whether null values can be accepted for this column (for rows belonging to a table).
UniqueA Boolean that determines whether duplicated values are accepted in this column (for rows belonging to a table).
ReadOnlyA Boolean that determines whether values in this column can be modified after the row has been added to a table.
DefaultValueThe default value for this column when a new row is added to the table.
ExpressionThe expression to be used for calculated columns.
AutoIncrementA Boolean that determines whether this is an auto-incrementing column (for rows added to a table).
AutoIncrementSeedThe starting value for an auto-incrementing column.
AutoIncrementStepThe increment value for an auto-incrementing column.
CaptionThe caption to be used for this column in the user interface.
NamespaceThe namespace for this DataTable, used when importing or exporting XML data.
PrefixThe XML prefix for the DataTable namespace.
ColumnMappingThe MappingType of this column, which is how this column is rendered as XML. It can be Element, Attribute, SimpleContent, or Hidden.
TableThe DataTable this column belongs to (read-only).
OrdinalThe position of this column in the DataColumnCollection (read-only).
ExtendedPropertiesReturns the PropertyCollection object used to store custom information about the DataTable (read-only).

The DataView Class

The DataView class represents a view over a DataTable object, a concept that doesn't really match any ADO object you might already know. For example, you can filter the data in a table or sort it without affecting the values in the original DataTable object. Or you can create a view on a table that does (or doesn't) allow insertions, deletions, or updates.

A DataView object contains a collection of DataRowView objects, which are views over the rows in the underlying DataTable object. You can insert, delete, or update these DataRowView objects, and your changes are reflected in the original table as well. Another major function of the DataView class is to provide data binding to Windows Forms and Web Forms. Table 21-5 summarizes the most important members of the DataView class.

Table 21-5 Main Properties, Methods, and Events of the DataView Class

CategoryNameDescription
PropertiesAllowDeleteTrue if rows can be deleted.
 AllowEditTrue if values in the DataView can be modified.
 AllowNewTrue if new rows can be added.
 ItemReturns the Nth DataRow (default member).
 CountReturns the number of rows in this view.
 RowFilterAn expression that determines which rows appear in this view.
 RowStateFilterA DataViewRowState enumerated value that determines how rows are filtered according to their state. It can be None, CurrentRows, OriginalRows, ModifiedCurrent, ModifiedOriginal, Added, Deleted, or Unchanged.
 SortA string that specifies the column or columns used as sort keys.
 ApplyDefaultSortTrue if the default sort order should be used.
 TableThe source DataTable.
 DataViewManagerThe DataView associated with this view (read- only).
MethodsAddNewAdds a new row and returns a DataRowView object that can be used to set fields' values.
 DeleteDeletes the row at the specified index.
 FindFinds a row in the DataView given the value of its key column(s); returns the row index.
EventsListChangedFires when the list managed by the DataView changes, that is, when an item is added, deleted, moved, or modified.

The DataRelation Class

The DataRelation class represents a relationship between two DataTable objects in the same DataSet. The relationship is established between one or more fields in the parent (master) table and an equal number of fields in the child (detail) table. Table 21-6 lists the main properties of the DataRelation class. (This class doesn't expose methods other than those inherited from System.Object.) Note that all properties except Nested are read-only.

Table 21-6 Main Properties of the DataRelation Class

NameDescription
RelationNameThe name of this relationship.
DataSetThe DataSet object this relationship belongs to.
ParentTableThe parent DataTable object.
ChildTableThe child DataTable object.
ParentColumnsAn array of DataColumn objects representing the keys in the parent table that participates in this relationship.
ChildColumnsAn array of DataColumn objects representing the keys in the child table that participates in this relationship.
ParentKeyConstraintThe UniqueConstraint object that ensures that values in the parent column are unique.
ChildKeyConstraintThe ForeignKeyConstraint object that ensures that values in the child table's foreign key column are equal to a value in the parent table's key field.
NestedA Boolean value that specifies whether child columns should be rendered as nested elements when the DataSet is saved as XML text (read/write).


Next



Last Updated: April 10, 2002
Top of Page