This action might not be possible to undo. Are you sure you want to continue?
This module introduces ADO.NET, the evolutionary next step for Microsoft® ActiveX® Data Objects (ADO). What You Will Learn • The difference between ADO and ADO.NET • The benefits of ADO.NET • ADO.NET core concepts and architecture, including the ADO.NET object model, introduction to the System.Data namespace, the DataSet, and data views; .NET data providers, and more Recommended Reading • "ADO+ Guides the Evolution of the Data Species" http://msdn.microsoft.com/library/techart/adoplus.htm • Microsoft ADO.NET newsgroup: microsoft.public.dotnet.framework.adonet
ADO.NET and the .NET Framework
ADO.NET is part of the Microsoft .NET Framework. If you break down the Framework into sections (common language runtime, base classes, data and XML, Web Services and user interface), then ADO.NET sits squarely in the data and XML section.
The short of it is that ADO.” if you will.” such as is found on a corporate local area network (LAN). For these types of applications. where users need to work with information that is up to the moment. ADO. ADO and long and for ADO. and changes to the data are posted to the data store immediately. to the data source. For example.NET Overview ADO vs. begin by Designed for connected access ADO is based on the concept of a 24/7 (24 hours.NET is. 7 days a week) “connected world. besides the name change. Let us looking at ADO. both have to be connected. . A typical scenario is a ticket-booking application.NET is the next step consisting of many enhancements. If two components need to share the same data. you might wish to design your data access around ADO. connect it to a data source—most often a database—and work. The RecordSet stays “plugged in.4 ADO. A model based on connected data can make it difficult and impractical to exchange data across application and organizational boundaries. You create a RecordSet. in an application that performs a high volume of updates with possible record contention. a connected data architecture can be very important. There are times when it is still useful to work with connected data.NET (1/2) ADO You may wonder what the difference between ADO. or a way must be devised for the components to pass data back and forth.
Data sharing via COM marshalling Sharing data between components in your application or elsewhere is done through COM marshalling. if you perform a joining query the resulting data is “flattened”. For example. Data types are bound to COM/COM+ data types A rather significant limitation of ADO is that the available data types are restricted to Component Object Model (COM) and COM+ data types. navigation is sequential. For an Internet-based solution. most useful data analysis or presentation requires views of your data that span multiple tables or data sources. .NET 5 However. That means that sometimes you need to fit a square peg in a round hole. this cannot be accomplished without performing a SQL JOIN. the BSTR type is really a stranger to all languages and only makes sense in the COM context. and other lower level languages you must use special COM run-time functions to create and destroy them. row-by-row. For C. For example. you should certainly look at ADO. the BSTR type is a null-terminated string whose leading WORD contains the length of the string. a connected architecture is impractical (if not impossible!) in the disconnected world of the Internet. RecordSet is one table that contains all the data The ADO RecordSet is limited in flexibility and functionality. in COM/COM+ programming the BSTR is typically used to represent strings that need to be interoperable across languages. Because a RecordSet is essentially a single result table. Using ADO. and rapid application development (RAD) environments like Microsoft Visual Basic® need explicit support in the runtime to handle these types. For those of you who do not know. C++. perhaps more impressive point is that ADO does not support an abstract data model. It is tied to the physical data source. This limits sharing of data to a COM or COM-friendly environment. any relations that may have existed are not relationally navigable.ADO. Unfortunately. this is a performance drag. It consumes memory and CPU power on the database server—precious resources especially with today’s Internet user demands.NET as your data access technology. Another. Thus. As you may or may not know.
6 ADO. binary) There are also problems with marshalling through firewalls. COM marshalling requires (COM) system services on the “other side” of the firewall (the server). but firewalls are often set up to block such traffic because it could pose a security threat. .NET Problems marshalling through firewalls (DCOM. because they tend to restrict the type of data that can pass through them.
NET is a disconnected one.NET in general. unlike the RecordSet. ADO.NET Designed for disconnected access In contrast to ADO.NET. Can model data logically! An additional improvement over ADO is that ADO. but more on this later. Data types are only bound to XML schema— No data type conversions required Considering the flexibility the DataSet affords. This is achieved through the successor of the RecordSet: the DataSet. This is accomplished through its use of XML schemata. the DataSet is not a data container capable only of stuffing rows of data into itself. As such. If you can describe it in the schema.NET (2/2) ADO. is designed with Internet technology. although not limited to creating Internet-based solutions. you can use it—and avoid data conversions! .NET 7 Overview ADO vs. the access model of ADO.NET provides the means to model your data abstractly. DataSet can contain multiple tables The DataSet can model data logically or abstractly because. You now have the ability to create an in-memory data schema that includes multiple tables and the relationships between them! Two intended results of this are that relational navigation is now possible and you can create views on multiple tables or data sources without performing a database JOIN.NET gives you the ability to use any data type. it should not surprise you that ADO.ADO. ADO. like .
unlike binary data (COM/COM+).” . Because XML is just plaintext it can more readily pass through firewalls without being burned. firewalls can inspect XML data —“it's just text. The reason is that. is plaintext: “Firewall friendly” The use of XML and XML schemata in ADO.NET also makes it possible to share data between DataSets and other components or applications—without limitation.8 ADO.NET XML. like HTML.
interpret. As you learned. you can establish a data access layer. Scalability through the disconnected DataSet On the scalability side of things. is human readable and decipherable text. because connections are not maintained for long periods. execute one or more queries. like much of .NET verses ADO in our comparison. and disconnect. ADO. However.NET brings the connected world of the Internet to your solutions through its disconnected model.NET. there is little possibility that database locking will occur. and work with.NET. This means you can create your application in independent layers. You can now design and implement your applications without the extra consideration toward resource loads on your database-server tier. XML is used throughout ADO.NET and this has its own benefits. Maintainability ADO. XML is used to represent and transfer all data in ADO. and is data that describes itself (metadata).ADO. . is built around the idea of separation of data logic and user interface. Simply: Connect.NET. by specifically using Service Components you can perform locking. For example. a business logic layer. Designing and building your application this way limits “collateral damage” when you update any given aspect of your solution.NET 9 Overview Benefits of ADO. and an interface façade (or user interface).NET We have already touched on the benefits of ADO. This makes it easy to share. For these reasons. Interoperability through use of XML XML is an open Web standard.
NET Overview Visual Studio. and then automatically generate the select. insert.NET dynamically creates code based on a schema (. for instance.10 ADO.NET uses this for statement completion. as well as compile-time type checking.Customer(“Jones”). ADO. Visual Studio. update and delete queries for you! The wizards also make creating DataSet objects based on your selection of tables .Balance to access the Customer table than by writing Table(“Customer”)(“Jones”).xsd) and generates a file (. Wizard Support Visual Studio.NET enables you to create typed DataSets in which you define the schema for the DataSet and its data.cs) containing the strongly typed DataSet. Microsoft Visual Studio. if you wish to select the “Balance” column for “Jones” from the “Customer” table it is certainly more intuitive to do so by writing DataSet.NET provides several “wizards” aimed to make rapid application development possible. For example.NET Enhancements Typed programming—a programming style Typed programming is a programming style in which enduser words are used to construct statements or evaluate expressions. These wizards enable you to visually select the tables you wish to work with from your data source.Column(“Balance”) The typed programming model is also easier to read and comprehend for both programmers and nonprogrammers! To this end.
ADO. There is plenty of additional wizard support for ADO.NET in Visual Studio. .NET. By using the designer in this way you create the DataSet and its corresponding DataTable objects and relations. but that it not the topic of this module.NET 11 automatic – by selecting “Generate appropriate object is generated. DataSet” the There is also an XML Designer that makes it easy to create data schemas.
NET are System.NET Object Model The ADO.Data. but in sum it is: DataSet and its related objects and the . SQLTypes. You also have the ability to modify the data source’s schema from your DataSet. you can create new tables.NET is organized into five main namespaces: • • • • • System. That is.NET Core Concepts and Architecture Core Concepts and Architecture The ADO. retrieve information.SqlTypes The core namespaces of ADO.SqlClient and System. Two other namespaces that are arguably part of ADO. update your cached data.NET data providers. and post it back to the data sources.Common namespace contains the classes that are common to all .Data.OleDb.Data and System.Data.NET-related Namespaces ADO. .NET that you will work with are System. store it (in an in-memory cache).NET object model is comprised of several namespaces.Data System.SqlClient System. The System.Data.Data. these are both optimized for use with Microsoft SQL Server™.12 ADO.Data.Data. ADO.Common System. these five namespaces provide you with the means to connect to data sources. Combined.OleDb System. make new relations.Data. and update the data source with the information.NET data providers.
NET as a pyramid in which the topmost. Below that you have the System.Data.SqlClient.Data namespace.Common. System.Data. . System.ADO.OleDb.Data. and System. main tier is the System.NET 13 Core Concepts and Architecture ADO.SqlClientTypes namespaces.Data.NET-related Namespaces You may think of ADO.
14 ADO.Data Namespace The ADO.Data namespace. System.NET object model System. System.Data is “all about data”! For this reason.NET and the data-centric namespace. is contained in the Contains the basis and bulk of ADO. Provides the means to work on and with your data! • It contains a myriad of classes for working with data • Ability to create views of your data • Means to logically represent your data • Enables the use of XML to view. and store data It is the means to work on and with your data! . share.NET As its name implies.Data is the centerpiece of ADO.NET Core Concepts and Architecture System.
DataViewManager Used to create one or more views (using DataView objects) on the DataTable objects of a DataSet • .ADO.NET 15 Core Concepts and Architecture Introducing the Objects… Following are a few of the objects that are “first class citizens” in the System. You will find yourself working with these classes regularly. • • • • • • System. this is similar to how a relation is created in a SQL database. As you will learn.NET DataSet In-memory cache of data and data-related information DataTable In-memory cache of a database table DataRow Used to manipulate a row in a DataTable DataColumn Used to define the columns in a DataTable DataRelation Used to relate two DataTables to each other.Data Contains the “main” classes of ADO.Data namespace.
This diagram does not show which objects a DataSet must contain but what it can—or more accurately. .NET Core Concepts and Architecture Putting the Objects Together… This diagram shows you how some of the classes in the System. The DataView and DataViewManager objects shown are meant to convey that one or more views may be created on any given DataTable. You may do this by specifying that one or more columns in two different tables are related. Notice that the DataTables are contained by the DataSet Tables container and the DataRelations are contained by the Relations container.Data namespace fit together with relation to the all-important DataSet.16 ADO. In this example we have a DataSet in which three DataTables have been added and two DataRelations. Access to members of the containers is achieved using array-style indexing. Note that the lines connecting the DataTables to the DataRelations are meant to show that a relation between the DataTables has been specified. It should be clear to you from this diagram that the DataSet is the ADO. Note that the DataColumn objects of each of the tables you wish to relate must be of the same data type.NET view of data. most likely will—contain. You may add the appropriate items to each of these containers using their Add methods.
When you think DataSet. Alternatively. manipulation and viewing of the data is obviously fast. you may create your own logical representation of the data. An in-memory cache of data from a data source A DataSet is an in-memory cache of data loaded from your data source or sources using one or more query commands. let us explore a little deeper into the DataSet. it is universal because it is designed to contain data from any data source.ADO. Because it is in memory. think “set of data” not “cache of data from the database"! Taken in this context. In other words. Well. Data. Common way to represent and manipulate data The real advantage that the ADO. it is a “universal data container. you should see the potential of using DataSets throughout your application solution—not only when querying a database but any time you need to manipulate or move data around. The DataSet does not restrict you to mapping directly to the physical data source layout.NET DataSet provides is that it is a common way to represent and manipulate data. .NET 17 Core Concepts and Architecture Working the Data – The DataSet Now that we have an overview of the DataSet and understand that it acts as the main component of System.” You may ask what “universal” means. Logical representation of data A DataSet is a logical representation of data depending on the query/result set. That source might as easily prove to be a component in your application as a database.
DataSet objects communicate using XML documents. and when you are ready to update the data source you simply reconnect to the data source and issue an update command. but the corresponding Customers. Again. which means they can communicate with just about anything! You will learn more about the reading and writing XML documents in ADO. and then close the connection. execute your query or queries.NET later. Addresses.NET Framework. called DataTables. So. XML used to read and write data and schema In the . the tables and relations you create in the DataSet need not be bound to those in the data source but may be your own logical representation. You can perform a query on your for customers whose addresses are in a particular region and also retrieve their credit card information. At this time. you can create tables in the DataSet. XML plays an important and pervasive role.NET For example. Addresses. suffice it to say that the DataSet stores and communicates using XML and XML schemata. Disconnected from the data source The DataSet is an in-memory cache designed to be disconnected from the data source. and CreditCards. and create relations between them. On the other hand. You can then work with the cached data. . assume your database has three tables: Customers. You simply connect to the data source using an OleDbConnection object (or SqlConnection object).NET be any different? As we have already learned. why should ADO. We have already learned some of the advantages of this disconnected philosophy.18 ADO. The result of your query would be stored in the DataSet. and CreditCards tables need not exist in the DataSet.
” In the case of the Tables property. Relations Returns the RelationsCollection of DataRelation objects.NET 19 Core Concepts and Architecture Properties & Methods of Interest Collections are used to add and remove tables and relations Before we discuss the properties of the DataSet. Samples will follow. the collection is of type DataTableCollection. You may then iterate over the collection to get each object it contains. Namespace Get or sets the namespace associated with the DataSet. You may also use a collection’s Add() or Remove() methods to add or remove objects. the collection used to hold any DataTable objects added to the DataSet. • • . Properties of Interest Now let us delve into some of the DataSet properties of interest.ADO. for instance. • Tables This property is used to retrieve the DataTableCollection. the general rule is that the collection’s type name is the property name appended with “Collection. When a property returns (or “gets”) a collection of items. representing logical relationships between tables in the DataSet. let us first talk about properties in general with a focus on those that return collections. This is used for scoping elements and data.
DataTable newTable = new DataTable( “Addresses” ).NET which is especially useful when reading or writing a DataSet’s XML schema or data Using Properties Sample The following code snippet uses the Tables property of the DataSet myDataSet to add a newly created DataTable to the DataSet. In the following example. ... // Iterate over the collection.Tables. myDataSet. DataTableCollection myDataTableCollection.20 ADO.Tables. the DataTableCollection of a DataSet is returned so that you may iterate over it to retrieve the DataTables that are contained in the DataSet. // Iteration not shown.Add( myTable). // Creation of the columns and rows of the // Address table is not shown. myDataTableCollection = myDataSet.
ADO.NET 21 Core Concepts and Architecture All About Data… Simply to reiterate a very important point: a DataSet is a Universal Data Container—It’s not just for databases! .
22 ADO.NET Core Concepts and Architecture The DataTable Maps DataSet data to a physical table in the data source You may create a DataTable object and map it to a data source’s table. Properties of Interest • Columns Gets the columns as a collection. it is logical that a one-to-many correspondence may exist via a common column. a CustID column in one table may have a corresponding column in another table. As a customer may have more than one address. if your data schema contains a table called Customers you can create a DataTable in the DataSet to correspond to the physical table in a one-toone manner. such as the customer name or ID. The choice is yours. An example would be a Customers table and an Addresses table (for customers). depending solely on what makes sense logically to you. . tables are often related to one another in different logical ways. This returns the ColumnsCollection containing any/all DataColumn objects. For example. Can be related to one another through DataRelations In a physical model of the database or other data schema. That is.NET facilitates creating this type of relation between DataTable objects with DataRelation objects. ADO. It is also possible to create DataTable objects that do not correspond to any table in the data source.
Constraints Returns the table’s constraints as a ConstraintsCollection. The contained combined objects comprise the table’s primary key.NET 23 • • • • • Rows Returns the rows of the DataTable. DataSet Returns the DataSet to which the DataTable belongs.ADO. These are the logical relationships of one table to other tables. Technically. . a RowsCollection of DataRow objects is returned. PrimaryKey Gets or sets the primary key of the table using an array of DataColumn objects. ParentRelations Gets the parent relations as a RelationsCollection.
1. Create a DataColumn.NET Core Concepts and Architecture System. 4. providing the column name and data type.Tables property to add the DataTable to the DataSet. Add the DataColumn to the DataTable. Use the DataSet.Data—DataSet and DataTable Create a DataTable using a DataSet. Repeat until satisfied! . 2. 3.24 ADO.
For example.NET 25 Core Concepts and Architecture Relating Data – The DataRelation Having already learned something about the DataRelation when you learned about the DataTable and DataSet objects. Used to relate two DataTable objects to each other The DataRelation object uses DataColumn objects to create the relation between two DataTables.ADO. A nice feature of DataRelations in ADO.NET is that you can name the relation anything you like. it would be logical (and easy to remember) if a relation between a Customers table and an Orders table were named CustomerOrders. one column cannot be of the integer type while the related column is of the character type. it is time to expand on DataRelation objects.NET simply because you can create relations by which to navigate! As DataRelation objects are created using two DataColumn objects. For instance. . making it easier to remember. one from the parent and one from the child DataTables. You will see more on DataRelations later. Makes relational navigation possible Relational navigation is possible in ADO. a connection by which to navigate exists. If you have any database experience. and use this name to refer to the relation later. it will be obvious to you that the DataType (the type of data) for both columns must be the same.
DataRelations are retrieved or set using the DataSet object’s Relations property or the DataTable object’s ParentRelations property. which is a collection of all DataRelation objects of a DataSet. Both properties return a RelationsCollection.26 ADO. .NET RelationsCollection used to hold/group DataSet’s relations As you have learned.
2. .NET 27 Core Concepts and Architecture Creating Relations With DataRelation Keeping in mind the previous example of creating DataTable and DataColumn objects. Create a named DataRelation using the columns. Add the relation to the DataSet using the DataSet’s Relations property. Three basic steps are all that are needed: 1. 3. let us explore how to create relations between the Customers DataTable and a second Orders DataTable object. Retrieve the DataColumn objects that you will base the relation on from the appropriate DataTable using the DataSet’s Tables property.ADO.
Two additional methods provided are: GetXml and GetXmlSchema. the DataSet is capable of reading and writing its data and schema as XML.28 ADO. industry standard that is popular among most software solutions providers.NET Core Concepts and Architecture XML and the DataSet DataSet can read/write XML for its data and/or schema As mentioned previously. such as Microsoft SQL Server 2000. The fact that it is designed to both contain and describe data (data that describes itself) makes it the perfect choice for a universal data container such as the DataSet! Furthermore. These methods return the data or schema as a string. the ability of a DataSet to both read and write data and schema as XML makes it possible for you to both create and modify data in a DataSet using XML or XML enabled solution. At this time. found both in Internet solutions and in traditional applications. XML-related DataSet Methods for Reading • ReadXml: Reads an XML schema and data into the DataSet • ReadXmlSchema: Reads an XML schema into the DataSet And for writing: The methods for reading XML into a DataSet of course have complimentary means of writing XML from a DataSet: WriteXml and WriteXmlSchema. . This is important if you consider that XML is an open. XML is pervasive.
if you will.ADO. They provide a “before and after” picture of things.NET 29 Namespace property: Sets the namespace for serialization Full support for SQL Server-style DiffGrams DiffGrams are an XML means to track changes to a DataSet's data and schema. .
30 ADO. .NET Core Concepts and Architecture Methods of Reading and Writing XML This code sample shows you how to use some of the XML-specific methods and properties of a DataSet.
ADO. DataRelation. . and Data…Views This slide provides an overview of the relationships between DataSet. DataTable. DataRelation. DataView and DataViewManager objects.NET 31 Core Concepts and Architecture DataSet.
New. • Sort Gets or sets the sort column or columns and the sort order for the table. ModifiedOriginal. ModifiedCurrent. None. OriginalRows. the default is ascending. For instance.NET Core Concepts and Architecture Viewing Data – The DataView Create multiple views on DataTable objects Using DataViews you can create multiple views on any given table. Deleted. • RowFilter Get or set the expression used to filter which rows are displayed. . Unchanged. you may have an Addresses table containing the primary and secondary addresses but wish to create two different views on the data: one for the primary and one for the secondary addresses.32 ADO. The possible values are any one of the following DataViewRowState values: CurrentRows. Bindable to user interface controls The DataView is designed so that you can bind it directly to Windows Forms or Web Forms UI controls. You may set the sort order to either ascending (“ASC”) or descending (“DESC”). • RowStateFilter Get or set the row state filter. Properties of Interest • Table Gets or sets the source DataTable for the view.
ADO. Specify a Sort and RowStateFilter on the view1 and view2 objects. . Bind a DataView (view1) to a DataGrid.NET 33 Core Concepts and Architecture Creating a DataView By Example This sample shows you how to: • • • Create two DataView objects (view1 and view2) on a DataTable (myTable). respectively.
34 ADO. . DataViewManager permits the creation of more complex views on related tables in a DataSet. Properties of Interest • DataViewSettings Returns a DataViewSettingsCollection object.NET Core Concepts and Architecture Viewing More Data . DataViewSetting objects cannot be added or removed by the user. • DataSet Used to get or set the DataSet to be viewed. Additionally. enabling you to set individual filters on each of the tables. Used to create multiple views on a DataSet This is a more advanced viewing feature than the DataView.DataViewManager Similar to a DataView but DataSet oriented Instead of setting a view on an individual table. Instead the properties of a DataViewSetting may be modified (see sample). each table may have its own filter or sorting settings.
NET 35 Core Concepts and Architecture DataViewManager By Example 1. Set the data source for the the DataGrid (dataGrid1) to the DataViewManager and then set the data member (i. Set the DataViewSettings on the DataTable “Orders” in the DataSet myDS to Sort in ascending (ASC) order on the CustID column. the table) that the DataGrid “looks upon” (i. Create a DataView on the Orders table. “Table1”). 3.e. Repeat steps 1-3 for the Customer table. Create a DataViewManager using an existing DataSet.e. . 2. 4. 5.ADO.
.NET Data Providers A collection of classes for accessing data sources Let us first step back from the ADO.NET managed provider The System.36 ADO.NET scope and into the broader .NET data providers: • • ADO: via the System.NET data providers In the .NET managed provider. and Microsoft Data Engine (MSDE). SQL Server 7. . Of course. Two . System.NET data providers are comprised of a collection of classes for accessing various data sources.SqlClient namespace The latter is optimized for SQL Server.OleDb namespace is the ADO.Data. Jet.OleDb is the ADO. they are the connection between DataSet objects and the data stores. it is the SQL Server managed provider.Data.OleDb namespace SQL Server: via the System. and SQL OLE DB providers.NET arena.Data. including: Oracle.NET Core Concepts and Architecture The (ADO).NET Framework you will find classes specifically optimized for SQL Server 2000. these classes are designed to provide connectivity to the data source.NET data providers implies. there is also a host of other classes for working with any OLE DB providers.Data. As the term .NET Framework there are currently two . Included in the .
ADO.NET 37 .
Data.OleDb are descendents that are siblings to each other.NET data providers.SqlClient. and function in nearly identical manners. perhaps “clone” is a better term.NET data providers. logically it takes on more of an ancestral role its classes are shared (or inherited) by the other . sound. as they look.NET Data Providers Hierarchy We revisit the System.Data pyramid discussed earlier but instead focus on the .NET data provider namespaces. you may think of them as identical twins. .NET . In fact.Data.38 ADO.Common namespace is a sibling to System. System. As you will recall.Data.SqlClient and System.Data. Both System. While in fact the System.Data is the data-centric root of the .NET Core Concepts and Architecture . They are indistinguishable except by prefix name and the fact that one is targeted specifically at SQL Server.OleDb and .
Open. You then can use the returned object to perform transactional operations: . Close a connection to a data source The OleDbConnection class is your connection to your data source. • • Additional functionality is also available. Represents a unique session with a data source This OleDbConnection class represents a unique session with a data source. Functionality and Methods to Perform Transactions OleDbConnection provides a BeginTransaction method that returns an OleDbTransaction object. It is used to: • Create a connection to a specified data source. Close a connection to the data source using the Close() method.NET data providers by looking at a few of the classes that handle connecting to the data source and issuing queries. by passing a data source connection string to the OleDbConnection or SqlConnection class constructor. Open a connection to the data source using the Open() method.ADO.NET managed provider unless otherwise specified.NET 39 Core Concepts and Architecture OleDbConnection and SqlConnection Let us now venture a little deeper into the . This discussion continues with a focus on the ADO. Create.
.40 ADO.NET • • CommitTransaction: Called to commit (and end) a transaction RollbackTransaction: Called to “undo” a transaction OleDbConnection Example This simple code snippet simply demonstrates the creation of an OleDbConnection object. using it to open a connection to the data source and then closing the connection.
It exposes a set of commands and a data source connection that are used together to fill a DataSet and update a data source. . the OleDbDataAdapter class has several properties designed to aid you.ADO. Means to modify the DataSet and data source As it is designed for issuing queries against the data source.NET 41 Core Concepts and Architecture OleDbDataAdapter Class (1/2) Bridge between the DataSet and the data source The OleDbDataAdapter inherits the functionality of the OleDbDataAdapter class. as you will see in a minute. which enables it to act as a bridge between the DataSet and the data store.
• InsertCommand Gets or sets a command used to insert records in the data source. such as FillData() and Update(). . You will find that you often use these methods when retrieving or updating your DataSet.42 ADO.NET Core Concepts and Architecture OleDbDataAdapter Class (2/2) Properties of Interest • DeleteCommand Gets or sets a command used to delete records in the data source. Inherits methods from OleDbDataAdapter class The OleDbDataAdapter class inherits methods. • UpdateCommand Gets or sets a command used to update records in the data source. • TableMappings Maps the a data source table to a DataTable in the DataSet OleDbCommands are retrieved or set by “command” properties Note that the “command” properties referred to are actually OleDbCommand classes that contain the queries to perform on the data source. • SelectCommand Gets or sets a command used to select records from the data source. from the OleDbDataAdapter class. You will learn more about this in the OleDbCommand section.
ADO.NET 43 .
44 ADO. StoredProcedure (the name of a stored procedure). . which may be either an SQL statement or the name of a stored procedure. • CommandTimeout The seconds until connection timeout. as you can see from the properties of interest. • CommandText Get or set the query (text) command. • CommandType Get or set how to interpret the command text. or TableDirect (the table name whose columns are returned). • OleDbTransaction Get or set the transaction in which the OleDbCommand is to execute (if any). Properties of Interest • ActiveConnection Get or set the data source connection.NET Core Concepts and Architecture OleDbCommand Class Represents a query to execute on the data source In addition containing the query to execute. The possible CommandType values are: Text (a SQL text statement). the OleDbCommand class provides a few additional items.
NET 45 Core Concepts and Architecture OleDbDataReader (1/2) Forward-only data access Designed only for reading data from a data source. the OleDbDataReader is a “simple class” providing forwardonly data access. “Lightweight” programming model Because its functionality is very specific (or limited).ExecuteReader You cannot actually instantiate the OleDbDataReader directly.Execute() method will instantiate and return it. As you will see in the sample. Ties up the OleDbCommand until it is finished reading Be aware that the OleDbCommand class cannot process any other requests while it is reading data.” This is especially true if you compare using the OleDbDataReader to using OleDbDataAdapter. it is “lightweight. you declare the OleDbDataReader and the OleDbCommand. . it blocks until it has finished. A point worth mentioning is that the OleDbDataReader is actually instantiated “behind the scenes” when you use the OleDbDataAdapter! Instantiated & returned by OleDbCommand.ADO.
Methods to retrieve data The OleDbDataReader provides the means to retrieve data from a specific column in the currently indexed row. use GetString(). Object  cols = new Object . reader.except for GetValue() and GetValues() . and so on).meaning that if the column you wish to retrieve is of String type. GetValues() returns the entire row as an array of Objects. The Read method is used to advance the reader to next record and returns false when no more records exist.NET Core Concepts and Architecture OleDbDataReader (2/2) The following are the properties and methods of interest when working with the OleDbDataReader. GetDecimal.46 ADO. .GetValues( cols ). GetValue() returns an object in its native format which you then must handle appropriately. All the Get…() methods are “type specific” . Properties of Interest • FieldCount Returns the number of fields in the result set. There are corresponding Get calls for each data type (GetInt32. • RecordsAffected Returns the number of affected records .
.NET 47 Core Concepts and Architecture OleDbDataReader Sample This sample shows you how to create and use an OleDbDataReader.ADO.
As you have learned, ADO.NET is a powerful successor to ADO, providing you with the same disconnected philosophy as the Web. Its architecture is flexible, allowing you represent your data in any logical way you wish. Furthermore, the ADO.NET use of XML for representing data carries forward the .NET philosophy and ensures that data can be communicated with a wide variety of data sources, objects, and applications.
Appendix—Exploring and Extending DuwamishOnline C#
The Duwamish Online store is one of the Enterprise Samples delivered with the Visual Studio.NET product. Duwamish implements a fictitious e-commerce bookstore complete with catalogue, personal profile management, and order handling. The Duwamish Sample is shipping in both a C# and a VisualBasic.NET version. Before we are going to start the walkthrough for the technologies that have been presented in this module, you will first learn how to install the Duwamish sample and how the sample is organized.
Appendix—Exploring and Extending DuwamishOnline C#
Installing the Sample (1/2)
Install the “Enterprise Samples” with Visual Studio.NET When you install Visual Studio.NET, make sure to include the “Enterprise Samples” into your installation. By default, they will be installed. If you did not install them, run setup again and simply add them. Location of the C# Version The C# version of the Duwamish sample is located below your Visual Studio.NET installation folder in the “.\EnterpriseSamples\DuwamishOnline CS” subdirectory. Location of the Visual Basic Version The Visual Basic version does, of course, reside in the “.\EnterpriseSamples\DuwamishOnline VB” directory. Installation Tasks Before you install the sample, you should check the following prerequisites: You should install the sample on Microsoft Windows® 2000 Server with SQL Server 2000 preinstalled. Duwamish Online uses the “English Query” feature of SQL Server, so you should make sure that this feature is installed for SQL Server 2000. For more detailed instructions you should read the Readme.htm file before proceeding. Once you are sure that your system has all of the required components, run the Duwamish.msi installer package by double-clicking it from the Microsoft Windows Explorer.
click Build Solution on the Build menu.NET using Open Solution on the File menu. the installer will proceed to install the database. If you want to install both demos. which you can open with Visual Studio.ADO. . the Web site. To run an initial build of the sample code. Web site. After installation is complete After the installation is complete.sln” file. you should install the first with the default values and choose different settings and directory names for the second one. so that they will not produce conflicts. The exact procedure and options will be obvious once you have installed the first version. Defaults should be OK for almost everybody Unless you want to install both the C# and Visual Basic versions side-by-side. and all related projects and code. you will find a “Duwamish. and code Once you have confirmed all settings. the default values should be OK. You may want to pay special attention to the database account (which must have administrative rights) and its password. Setup will install database.NET 51 Appendix—Exploring and Extending DuwamishOnline C# Installing the Sample (2/2) The installation wizard will guide you The installation package will start the installation wizard that will take you through all necessary steps.
.52 ADO. while the SystemFramework supplies auxiliary functionality for diagnostics and other technical tasks.NET Appendix—Exploring and Extending DuwamishOnline C# Duwamish Architecture Overview The architecture of Duwamish is mostly equivalent to what the enterprise templates of Visual Studio. which is being used by the BusinessRules and BusinessFacade to retrieve and store data. accessing all functionality through the BusinessFacade. Data is communicated throughout the layers using objects that are being provided by the Common module. All access to the database is essentially encapsulated in the DataAccess module.NET will generate for you as a skeleton. The Web module implements the user interface for the application.
It contains diagnostic utility classes. Also common to the entire system are the definitions for the catalogue (Books. Categories) and the order system (Customer. Duwamish7. . pre and post condition checking. All of the code in this project is generally useful and applies to projects beyond the scope of Duwamish. internal relational view of the Duwamish data that’s being mapped to a physical data store by the DataAccess layer (next slide).Common The Common namespace (and subproject) contains all configuration options that are common to all parts of the system. While the data is held in ADO. OrderData) and consequently they are located in this shared project that is being used by all layers. and dynamic configuration tools. The Common namespace provides its own.NET DataSets.SystemFramework The SystemFramework contains all utility classes that are implemented to serve a specific technical purpose but are not immediately related to the business code.NET 53 Appendix—Exploring and Extending DuwamishOnline C# Common Components Duwamish7. this should not be confused with being the actual database layer.ADO.
NET Appendix—Exploring and Extending DuwamishOnline C# Duwamish7. Uses ADO. .NET infrastructure and uses the SQL Server managed provider to access the data store.NET architecture The project builds on the ADO. providing a central point for maintenance if the underlying data model needs to be optimized or extended.Data namespace to the physical layout of the underlying database.54 ADO. DataAccess uses OleDbDataAdapters bound to the DataSets provided by the Common.Data subsystem. To retrieve and manipulate data. the sample uses only a minimal set of “ad-hoc” SQL commands and relies heavily on stored procedures. The DataAccess module maps the common definitions for the internal data representation that are defined in the Common.DataAccess Contains all database-related code The DataAccess namespace contains all databaserelated code in Duwamish. which are substantially faster. Optimized for performance using stored procedures To optimize performance.
It validates data. All data access performed through DataAccess All modifications that are being made to the underlying data store are performed through the DataAccess layer.BusinessRules Implements all business rules The BusinessRules layer serves to implement all logic that is mandated by the system requirements. .NET 55 Appendix—Exploring and Extending DuwamishOnline C# Duwamish7. implements calculations. and performs the manipulation of data.ADO.
The BusinessFacade provides consistent. .BusinessFacade Implements logical business subsystems The BusinessFacade sits on top of the BusinessRules and provides a logical subsystem view. all manipulation is validated and performed through the BusinessRules.NET Appendix—Exploring and Extending DuwamishOnline C# Duwamish7. While data is read through the DataAccess layer.56 ADO. separate interfaces to the customer system. and the product system. the order system.
NET architecture The UI is built on top of ASP. custom Web controls. all of the data displayed to the user and all interactions run through the BusinessFacade.NET innovations. Uses ASP. All functionality accessed through BusinessFacade Of course.Web Implements the user interface for Web access The Web namespace implements the full user interface for the application.NET using Web Forms.ADO.” and many more ASP. This layered model enables reusing the entire back end for a shop with a radically different look and behavior or to expose parts of the application as a Web Service or a Windows Forms application. . validation.NET 57 Appendix—Exploring and Extending DuwamishOnline C# Duwamish7. “code behind forms.
NET Demo: Duwamish in Action .58 ADO.NET Appendix—Exploring and Extending DuwamishOnline C# Shop at Duwamish Online.
and OrderData. each of these defines a class that contains a DataTable. The Common project is the logical first stop on this tour. bring both up by clicking Solution Explorer and Class View on the View menu. Looking at the Common project you will notice that there are four .NET 59 Appendix—Exploring and Extending DuwamishOnline C# Exploring ADO. At this point it is assumed that you could successfully install the Duwamish sample for C# and that you are able to open the solution file “Duwamish.NET that are used in this walkthrough. To make navigation a bit easier and to allow us to more easily find what we want to show you.NET in action.NET Features in Duwamish Online To familiarize ourselves with the Duwamish sample code and to see ADO. as it is where we find the DataSet support in Duwamish.ADO.NET. In fact. we’re first going to take a brief tour through the various building blocks.cs files: BookData. On the upper right side of your Visual Studio.sln” using File/Open Solution in Visual Studio. Common First. go to the Solution Explorer. CategoryData. we’re first going to identify the two key tools in Visual Studio. CustomerData. If you can’t find them there.NET window you should see a number of tabbed. overlapped tool windows—try locating the Solution Explorer and the Class View windows. . The Duwamish sample consists of six separate projects—one for each subsystem that we’ve seen in the architectural overview.
public const String NAME_FIELD = "Name". CTRL+-O. the DataTable’s columns collection is retrieved.Columns. Before we get ahead of ourselves. The CustomerData class implements two public methods (constructors) that build a DataTable to hold the customer data and one “helper” BuildDataTable. you can find these at the top of the class declaration. It should be obvious from the declaration what the “Customers” data member is: The name of the table to be created. public class CustomerData that implements a simple wrapper around Customer data. Let us concern ourselves only with a subset to keep things simple: public const String CUSTOMERS_TABLE = "Customers".Common. To get a better idea of the code structure. Scanning down to the BuildDataTable definition.cs compilation unit (file). Now. let us first look at data members of the CustomerData class. use the key sequence CTRL+M.. Here we can see that the DataTable is created using the Customers string: DataTable Table DataTable(CUSTOMERS_TABLE). if we examine the body of either of the CustomerData constructors we will notice a call to the private method BuildDataTable.Data. The others may be less obvious.cs in the Common project. public const String ADDRESS_FIELD = "Address". and the subnamespace for this project is Duwamish7.cs defines a single.. Beneath the namespace declaration you’ll see the using declarations for all namespaces that are being used and referenced within the CustomerData. public const String EMAIL_FIELD = "Email". //. This is needed in order to add columns to the table. we come to the interesting part. or select Edit/Outlining/Collapse to Definitions. . The first thing you’ll notice is that the Duwamish team used cascaded namespaces to organize their code into logical groups. = new Next. ColumnsCollection Columns = Table. As we scroll down we find that CustomerData.60 ADO. These are the names of the table columns (the DataColumn names). The base namespace for the entire Duwamish sample is Duwamish7.NET We will start exploring the code by opening the file CustomerData.
NET 61 With the ColumnsCollection in hand.TableMappings. Next.Tables. It performs queries on the data source using a SQLOleDbDataAdapter class and the CustomerData class declared and defined in the CustomerData. CustomerData.ADO. the purpose of this statement is to map the data source’s table to a corresponding DataSet: CustomerData. Looking into the method body. m_DSCommand. As we scroll down we find that Customers. The last line of the method adds the new DataTable to the DataSet: this. more interesting.Add(Table). m_DSCommand. DataAccess We will start exploring the DataAccess project by opening the file Customers. Customer. Here you will find the instantiation of the SQLOleDbDataAdapter and. or in this case. The Customers class is designed to manage Customer information. let us first look at data members of the class and note the declaration of a SQLOleDbDataAdapter object. each DataColumn is added to the DataTable using the collection’s Add method.cs defines a single. of type CustomerData which we know to be the DataSet.CUSTOMERS_TABLE ). = . common wrapper around data access for information on Customers. public class “Customers” that implements a simple. The first thing we need to note is that the UpdateCustomers method takes one “in” parameter.cs. we won’t explore them here. we see that the update command must first be created.Add ( "Table". Now look at the UpdateCustomers method responsible for synchronizing the information in the CustomerData with the database Customer table. retrieved. look into the Customers constructor. As the well-commented code conveys.UpdateCommand GetUpdateCommand(). protected SQLOleDbDataAdapter m_DSCommand.cs file. The other classes in the Common project are quite similar. the use of TableMappings. Before we get ahead of ourselves. This data member is used to issue the queries to the data source and DataSet.
CustomerData. it commits the data changes made to the DataSet: Customer.62 ADO.NET. Its separation of Common and DataAccess make it easy to explore and learn on your own. Duwamish lends itself to exploring ADO. . The code of course checks for update errors and if none occur.Update( Customer.AcceptChanges().NET Next we see that the SQLOleDbDataAdapter calls the Update method to update the records in the data source: m_DSCommand. The Update method takes two parameters: the DataSet as the source and the data source table used for the table mappings.CUSTOMERS_TABLE ). That’s it! As you can see.
Visual Basic. . Microsoft.ADO. © 2001 Microsoft Corporation. The names of actual companies and products mentioned herein may be the trademarks of their respective owners. and Windows are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. All rights reserved. ActiveX. Visual Studio.NET 63 Legal Notices Unpublished work.
This action might not be possible to undo. Are you sure you want to continue?