Upload
godwin-ariwodo
View
224
Download
0
Embed Size (px)
Citation preview
8/8/2019 App Dev Ado
1/40
Introduction toADO.NET
Understanding ADO.NETCopyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Understanding ADO.NET
Introduction to ADO.NET
Sample Chapter*
*To obtain a complete copy of this course, visit www.appdev.com or call 800-578-2062.
8/8/2019 App Dev Ado
2/40
Introduction toADO.NET
Understanding ADO.NETCopyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Welcomeand thank you for choosing Application Developers Training Company (AppDev) toguide you through an in-depth exploration of the powerful features ofMicrosoft ADO.NET.
At AppDev, we are committed to delivering quality training to programmers and developers.AppDev is a member of the Microsoft Certified Solution Provider network and we provide service
and training for Microsoft product users. We have trained over 50,000 developers since we begantraining in 1993, proving that AppDev students learn what they need to become efficient andeffective developers.
The key to a successful learning experience is comprehensive courseware that you can easilyunderstand and apply to your work environment quickly. We are sure you will find our coursewareinvaluable as a guide throughout this seminar and as a reference tool in your future projects.
Founded by application developers for application developers, AppDev offers you the mosteffective and comprehensive training in North America for Microsoft .NET, Access, Active ServerPages, Visual Basic, VBA, Visual FoxPro, Visual InterDev, SQL Server, Developing Applicationswith Access and SQL Server, and XML. Our instructors are practicing developers who are
recognized experts, successful authors, sought after speakers, and experienced trainers ofapplication development techniques. They put their development experience to work with our
proven courseware to help you build your skills for the future. We are pleased to offer you this
opportunity to take advantage of their expertise to help you masterADO.NET.
AppDev holds seminars throughout the United States and our multiple course offerings, locations,
and dates provide you with many ways to fit AppDev training into your busy schedule. If you cantfind a time or date that works for your company or department, we can bring customized training to
you. For groups of six or more, we will send one of our qualified instructors to your location toteach courseware specifically tailored to your organizations needs.
We hope you find todays course beneficial in your effort to enhance your ADO.NET development
skills. Keep us in mind should you decide to further your education with this excellentdevelopment product. If you have any questions or comments about this course or other trainingthat we offer, please dont hesitate to call us at 1-800-578-2062. You can also visit our Web site athttp://www.appdev.comwhere you can view course schedules, outlines and descriptions, or even
look over some sample courseware.
7610 Executive Drive Eden Prairie, MN 55344
PH (800) 578-2062 (952) 943-1363 FAX: (952) 942-8452 www.appdev.com
8/8/2019 App Dev Ado
3/40
Introduction to ADO.NET
Understanding ADO.NET 1-1Copyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Introduction to
ADO.NET
Objectives
Use the Wizards in Visual Studio .NET to create ADO.NET code and
bound forms.
Investigate the ADO.NET object model.
Learn about .NET data providers.
The files associated with this chapter are located in the following folders:
{My Documents}\ADONET\Intro
{My Documents}\ADONETLabs\IntroLab
{My Documents}\ADONETLabs\IntroLabCompleted
8/8/2019 App Dev Ado
4/40
Introduction to ADO.NET
1-2 Understanding ADO.NETCopyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
ADO.NET Code Created by VisualStudio
One of the advantages of using Visual Studio .NET to create data-bound
applications is that the development environment provides components and
wizards to automate the creation of data objects. The Data Form Wizard
creates a complete data-bound form that is fully functional, fetching data from
a database, creating navigation buttons, allowing you to perform inserts, edits
and deletions, and saving changes back to the database. The form isnt
perfectbut it can save you a lot of time.
The Data Form Wizard
The following demonstration walks you through the steps of using the Data
Form Wizard to create a Windows form that displays and allows you to edit
data from the Northwind Orders and Order Details tables. The completed
example in the Intro.sln solution is named frmWizardyou may want to
create your own example using another name for the finished form.
Try It Out!
Follow these steps to run the Data Form Wizard:
1. Right-clickon the project in the Solution Explorer window andchoose Add|Add New Item from the menu.
See frmWizard inIntro.sln
8/8/2019 App Dev Ado
5/40
ADO.NET Code Created by Visual Studio
Understanding ADO.NET 1-3Copyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
2. Select Data Form Wizard, as shown in Figure 1. Name the form and
clickOpen. This launches the wizard.
Figure 1. The Data Form Wizard.
8/8/2019 App Dev Ado
6/40
Introduction to ADO.NET
1-4 Understanding ADO.NETCopyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
3. ClickNext to bypass the introductory screen. Select the Create a new
dataset named option and name it dsOrders, as shown in Figure 2. If
you are running the wizard in the Intro.sln project, name it dsOrders1
to avoid conflicts with the completed solution. ClickNext.
Figure 2. Naming the new DataSet.
4. Click the New Connection button. Set the Data Link properties to
connect to the Northwind database in SQL Server. You can type a dot
in the server name combo box to connect to the local instance of SQL
Server, as shown in Figure 3. An alternative is to type (local) instead.ClickOKin the dialog box, and clickNext in the wizard.
8/8/2019 App Dev Ado
7/40
ADO.NET Code Created by Visual Studio
Understanding ADO.NET 1-5Copyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Figure 3. Creating a new connection to the SQL Server Northwind database.
5. Select the Orders and Order Details tables by moving them to the
right-hand pane shown in Figure 4, and clickNext.
Figure 4. Selecting the Orders and Order Details tables.
8/8/2019 App Dev Ado
8/40
Introduction to ADO.NET
1-6 Understanding ADO.NETCopyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
6. Since theres more than one table involved, you need to create a
relationship so that the order details can be displayed as child records
for each order. Figure 5 shows the wizard with a named relationship
relOrdersDetails. The Parent table is Orders, and the Child table is
Order Details. The primary/foreign key relationship is on the OrderID
column. This reflects the relationship between the two tables in the
Northwind database.
Figure 5. Configuring the relationship between Orders and Order Details.
8/8/2019 App Dev Ado
9/40
ADO.NET Code Created by Visual Studio
Understanding ADO.NET 1-7Copyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
7. Click the right-arrow button (>) to add the relation to the Relations
box on the right side of the dialog box. It should now look like Figure
6. ClickNext.
Figure 6. Creating the relOrdersDetails relationship.
8. You then need to specify which columns youd like displayed on the
form. If you dont want the finished form to appear to be too cluttered,
de-select some of the columns in the Orders table, as shown in Figure
7. The values in the Orders table will be displayed in TextBox controls
on the finished form, and the values in the Order Details table will be
displayed in a DataGrid control. ClickNext.
Figure 7. Selecting columns for display on the form.
8/8/2019 App Dev Ado
10/40
Introduction to ADO.NET
1-8 Understanding ADO.NETCopyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
9. The wizard provides several options for laying out the data on the
form. For this example, select the Single record in individual
controls option and add all of the options for additional controls, as
shown in Figure 8. Dont worrythe order details will still be
displayed in a DataGrid control, while the column values from each
order will be displayed in a TextBox control. ClickFinish.
Figure 8. Selecting controls for the form.
8/8/2019 App Dev Ado
11/40
ADO.NET Code Created by Visual Studio
Understanding ADO.NET 1-9Copyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Figure 9 shows the finished form in the designer. It may not look like
much estheticallyit could use a helping hand with form layoutbut all
of the controls on the form are fully operational. Note that there are four
separate components in the tray at the bottom of the form designer. These
components are used to create the ADO.NET objects needed to retrieve
and cache the data.
Figure 9. The frmWizard form in Design view.
8/8/2019 App Dev Ado
12/40
Introduction to ADO.NET
1-10 Understanding ADO.NETCopyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
10. To test the form, set it as the startup form for the project. Figure 10
shows the completed frmWizard at runtime (after the controls have
been slightly re-arranged).
Figure 10. The form the wizard creates at runtime.
If you play with the form, youll find that all of the controls work. However,
its not too difficult to break the form and cause a runtime error by clicking the
buttons in the wrong order. In a real-world application, youd want to put in
some state management for the form and more robust error handling.
The Code Generated by the Data Form Wizard
One thing that sets data binding in .NET apart from data binding in earliertechnologies is that the Data Form Wizard simply writes codeit does not
create any ActiveX controls, or black box objects that you have no control
over. You can examine the code generated to create the components displayed
in the tray by expanding the Windows Form Designer generated code region
in the code window.
Figure 11 shows a partial view of the code in this normally hidden region. This
code executes when the form loads. Dont worry about the details for
nowyoull have a chance to explore the ADO objects used later on.
See frmWizard.vb
8/8/2019 App Dev Ado
13/40
ADO.NET Code Created by Visual Studio
Understanding ADO.NET 1-11Copyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Figure 11. Code generated by the Data Form Wizard.
Not all of the wizard-generated code is contained in the hidden region. Figure
12 shows the section of code the wizard wrote that updates the database.
Figure 12. Wizard-generated code that updates the database.
All of the code generated by the Data Form Wizard is fully commented, and
examining it can help you learn more about how ADO.NET works. The
ADO.NET classes, methods, and properties used in this code will be covered
in detail in the remainder of this course.
8/8/2019 App Dev Ado
14/40
Introduction to ADO.NET
1-12 Understanding ADO.NETCopyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
The DataSet
In addition to creating the form, the wizard also creates an additional object,
dsOrders.xsd, which contains schema information about the data being used.
When you double-click it to open it in the designer, there are two views, one
graphical and one XML. Figure 13 shows the graphical view.
Figure 13. The schema for the DataSet in graphical view.
Click the XML tab at the bottom of the designer and you can see the XML
notation for the schema information, as shown in Figure 14.
Figure 14. Schema information created by the wizard.
In addition to the XML schema file, the code also creates a Visual Basic file
named dsOrders.vb. Together, these comprise what is called a typed DataSet.DataSets are used for caching data after it has been retrieved from a data
source, and typed DataSets contain extra information about the schema, or
See dsOrders.xsd
8/8/2019 App Dev Ado
15/40
ADO.NET Code Created by Visual Studio
Understanding ADO.NET 1-13Copyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
structure, of the data, allowing them to run more efficiently and to be easier to
work with in code.
The Data Adapter Configuration Wizard
If you look at frmWizard in the designer, youll note the two components in
the tray below the formOleDbDataAdapter1 and OleDbDataAdapter2.
OleDbDataAdapter1 is used to fetch the data for the Orders table, and
OleDbDataAdapter2 is used to fetch the data for the Order Details table. There
are three different ways to modify the settings for these data adapters: the
Properties window shown in Figure 15, the Data Adapter Configuration
Wizard, or code. The Properties window and the Data Adapter Configuration
Wizard are just easy ways to modify code. You can also launch the Data
Adapter Configuration Wizard from the Configure Data Adapter link at the
bottom of the Properties window.
Figure 15. Data Adapter properties.
See frmWizard
8/8/2019 App Dev Ado
16/40
Introduction to ADO.NET
1-14 Understanding ADO.NETCopyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Try It Out!
You can also launch the Data Adapter Configuration Wizard by right-clicking
on the OleDbDataAdapter1 component in the tray and choosing Configure
Data Adapter from the menu. Follow these steps to complete the wizard:
1. When the wizard launches, click the Next button to bypass the
introductory screen.
2. You can then choose to use the existing connection or click the New
Connection button to create a new one, as shown in Figure 16. In this
case, the existing connection works just fine. ClickNext.
Figure 16. Selecting the database connection.
3. The following wizard dialog box, shown in Figure 17, allows you to
choose from the following options: Use SQL statements, Create newstored procedures, orUse existing stored procedures. The first
option, using SQL statements, is the default. If you choose the second
option, the wizard will create stored procedures in the SQL Server
database to select and modify the data, and use those instead of direct
SQL statements. The third option, Use existing stored procedures,would work only if you had already created stored procedures in the
SQL Server database. ClickNext.
8/8/2019 App Dev Ado
17/40
ADO.NET Code Created by Visual Studio
Understanding ADO.NET 1-15Copyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Figure 17. Choosing query options.
4. The next dialog box, shown in Figure 18, displays the base query
selecting all of the columns in the Orders table. To modify the query,
click the Query Builder button.
Figure 18. The query used for selecting data.
8/8/2019 App Dev Ado
18/40
Introduction to ADO.NET
1-16 Understanding ADO.NETCopyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
5. The Query Builder shown in Figure 19 allows you to modify the
SELECT statement by clicking on the check boxes next to each
column. You can access other menu options by right-clicking in the
builder. The Run menu item displays the finished result set. ClickOK
when finished.
Figure 19. Modifying the query.
8/8/2019 App Dev Ado
19/40
ADO.NET Code Created by Visual Studio
Understanding ADO.NET 1-17Copyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
6. Click the Advanced Options button. This dialog box determines
whether data can be modified in the database by choosing the
Generate Insert, Update and Delete statements option, as shown in
Figure 20. The Use optimistic concurrency option means that the
code generated will check the database to see if another user has
modified the data since the data was fetched. ClickOKand then
Finish.
Figure 20. Determining what happens when data is modified.
If youve made any changes in the wizard, then the code in the form will be
automatically updated to reflect your changes.
TIP: The wizards create connection strings for you that use your machine name as
the Workstation ID setting, as shown in Figure 21. If you plan to distribute
the form to other users, this may cause the project to fail since the
Workstation ID will be different. Once youre ready to distribute the
application, you can delete the Workstation ID setting in your code with no ill
effects. It is not exposed in the wizard dialog boxes or in the Properties
window.
Figure 21. The Workstation ID is hardwired by the wizards.
8/8/2019 App Dev Ado
20/40
Introduction to ADO.NET
1-18 Understanding ADO.NETCopyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
The ADO.NET Object Model
In order to understand the code that is created for you by the wizards in Visual
Studio .NET, you have to understand the ADO.NET object model. It works
very differently from older object models such as DAO and ADO, so itshelpful to understand the problems with the older object models and the needs
that drove the development of ADO.NET.
The Evolution of ADO.NET
ODBC
Microsofts first technology for providing generic data access was ODBC
(Open Database Connectivity). ODBC has been very successful, but it isdifficult to program against because it relies on old-style function
callssimilar to the Windows API. So soon after ODBC was first developed,
Microsoft began work on object-based methods that would be easier for
programmers to use.
DAO
Microsofts first object-based API for data access was DAO, which was
developed solely in relation to the Jet database engine. You could use DAO
from within Microsoft Access, or from Visual Basic to access data stored in a
Jet database. DAO worked well in a single-tier application where both the Jet
database and the application were running on the client computer, even if the
data was stored remotely on a file server.
RDO and ODBCDirect
However, DAO didnt work as well with other data sources, such as SQL
Server, because it required an instance of the Jet database engine to
communicate with the database server using ODBC, which added substantial
overhead. So Microsoft added RDO for Visual Basic developers, and
ODBCDirect for Access developers needing to access ODBC data sources
more efficiently.
ADO
The last product in the chain was ADO, which was designed as an all-purpose
API capable of accessing data in databases, Active Directory and email stores,
among others. The OLE DB interfaces that underlay ADO were designed to
provide generic access to all types of data, not just relational data.
8/8/2019 App Dev Ado
21/40
The ADO.NET Object Model
Understanding ADO.NET 1-19Copyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
ADO was designed to handle the needs of client-server applications before
Web applications became common. Although ADO supports disconnected
recordsets, ADO recordsets dont travel well across the Internet, requiring
COM marshaling to transmit them among the tiers in an n-tier application. Not
only does this require specialized code, it also prevents data from being shared
with applications on non-Windows platforms. In short, ADO works best in a
Windows-only environment, and isnt well suited to the Internet.
ADO.NET
When Microsoft designed ADO.NET, they based it on an entirely new
programming model that is completely different from that of ADO. The name,
ADO.NET, may mislead you into thinking that ADO.NET is simply the next
version of ADO, but nothing could be further from the truth. Instead of being
based on COM and Windows, ADO.NET is based on the .NET Framework
and XML, and it is designed around working with disconnected data in an n-
tier environment. Figure 22 diagrams the evolution of ADO.NET over the
years.
Figure 22. The evolution of ADO.NET.
ADO.NET provides the following benefits:
Scalability
Interoperability
Ease of programming
Performance
8/8/2019 App Dev Ado
22/40
Introduction to ADO.NET
1-20 Understanding ADO.NETCopyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Scalability
More concurrent users can be supported using the disconnected model
employed by ADO.NET. Data is retrieved from a data store read-only and the
connection is closed. If data needs to be written back to the data store, another
connection is opened, the data source is modified, and then the connection is
closed again. Also, working with stored procedures is much easier inADO.NET than it was in ADO, and stored procedures provide the most
scalable and secure way to access and modify server data.
Interoperability
ADO.NET uses XML under the covers for all data transport. This allows you
to request data and move it from one place to another without requiring
specific APIs, software, or connectivity. XML has no runtime/transport
requirements, and no special code is required to marshal data across the
Internet.
Ease of Programming
The central object for managing data in ADO.NET is the DataSet, which better
reflects the structure of the underlying data through its DataTable and
DataRelation objects, which will be discussed in detail in the next section.
Typed DataSets provide increased safety and convenience when programming,
and ADO.NET in general ensures that data access technology is uniform and
that all components share common types, design patterns, and naming
conventions.
ADO combined many different capabilities in one objectthe recordset. In
ADO.NET these capabilities have been factored out among several more
specialized objectsDataTables for caching data, DataReaders for retrievingread-only data, and DataAdapters for filling DataTables and sending changes
back to the database.
Performance
The elimination of COM when marshaling data results in significant
performance benefits. In addition, ADO.NET provides data-engine-specific
providers for SQL Server and more recently, Oracle. The SqlClient provider in
ADO.NET takes advantage of SQL Servers native Tabular Data Stream
(TDS) protocol, which provides performance benefits that go beyond the
capabilities of an all-purpose provider such as ADO. The interfaces are the
same for all data sources, but the implementation can be tailored to optimizeperformance for each one with more freedom than was available in OLE DB.
8/8/2019 App Dev Ado
23/40
The ADO.NET Object Model
Understanding ADO.NET 1-21Copyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Connected and Disconnected Objects
The ADO.NET architecture makes it ideal for disconnected, n-tier
applications, where the central concept is working with a disconnected set of
data. Figure 23 shows a simplified diagram of the ADO.NET object model,
reflecting its division into two separate parts. On the left are the .NET DataProvider objects, which communicate with the database and which are
different for each data source. On the right are the disconnected objects used
for caching and managing datathese objects can work directly with XML,
they must go through a provider-specific DataAdapter to work with other data
sources.
Figure 23. The ADO.NET object model.
.NET Data Provider Objects
The objects shown in the box on the left side of the diagram in Figure 23 are
all directly related to connecting to databases and either fetching or modifying
data. These objects are always part of a specific .NET data provider, of which
two shipped with the .NET Framework:
System.Data.OleDb: Used for working with any OLE DB data
source. It also supports existing ADO unmanaged providers (versions2.6 and earlier).
System.Data.SqlClient: Designed to be used specifically with SQL
Server 7.0 or later.
Newer additions available for download from Microsoft include ODBC and
Oracle providers. In addition, providers are becoming available from third
parties for DB2, MySQL, Sybase, and all the other common data engines.
8/8/2019 App Dev Ado
24/40
Introduction to ADO.NET
1-22 Understanding ADO.NETCopyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
The DataAdapter
TheDataAdapterrepresents a set of data commands and a databaseconnection. It can fill a DataTable object or a set of DataTables in a DataSet
by using its Fill method, and it transfers changes performed on DataTables
back to the database by using its Update method. A DataAdapter has four
Command properties:
SelectCommand
DeleteCommand
InsertCommand
UpdateCommand
Each of these properties contains a Command object that the DataAdapter
object uses for selecting or modifying data. You use the Fillmethod to execute
the SelectCommandto populate a DataSet. You call the Update method to go
through the rows in a DataTable and use the appropriate commands to perform
deletions, inserts, or updates, based on the changes that have been made to the
data since it was retrieved or last updated.
The Connection object represents the connection to the database, allowing youto open and close connections, which are pooled automatically and can be
made part of transactions.
The Commandobject allows you to execute provider-specific commands forretrieving or modifying data, using parameters if necessary.
TheDataReaderobject is analogous to a forward-only, read-only, server-sideADO Recordset. It is designed to fetch records from the data source in a
stream as quickly as possible.
Each data provider contains its own specialized versions of these classes. In
reality there is no DataAdapter objectonly a SqlDataAdapter, anOleDbDataAdapter, etc. The same specialization and naming applies to the
Connection, Command, Parameter, and DataReader objects.
8/8/2019 App Dev Ado
25/40
The ADO.NET Object Model
Understanding ADO.NET 1-23Copyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
.NET Data Providers
In this course, youll be working primarily with the System.Data.OleDb
provider and the System.Data.SqlClient provider. Figure 24 shows the classes
contained in the OleDb and SqlClient providers as viewed in the Object
Browser in Visual Studio .NET.
Figure 24. System.Data.OleDb and System.Data.SqlClient classes.
Even though you ran the Data Form Wizard against data in a SQL Server
database, it still used the OleDb provider to create all of the code in the form.
The downside of using wizards and builders in general is that you sacrifice full
control and efficiency. Although its more work, it is more efficient to create
your ADO.NET objects by hand, which youll learn to do in subsequent
chapters in this course. In some cases, you can use the wizards to get you
started, and then modify the code that they generate.
The OleDb and SqlClient providers are the only ones that shipped with the
product when version 1 was released. Since then, however, Microsoft has
released providers for ODBC data sources and for Oracle. In addition, several
third-party vendors have also created specialized .NET providers for MySQL,Sybase, and other data engines. A provider that is specifically tailored for your
database engine will usually provide better performance than a generic
provider like the ones for OleDb or ODBC.
8/8/2019 App Dev Ado
26/40
Introduction to ADO.NET
1-24 Understanding ADO.NETCopyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
The Data-Caching Objects
The objects shown on the right side of the diagram in Figure 23 do not depend
in any way on the data sources you are working with. In fact, they know
nothing about the database and are never directly connected to it. You can
combine data from many different sources in a single DataSet. You use the
DataSet and the other object types that it contains as an in-memory cache, to
hold and manipulate data, or to bind data to controls.
ADataSetcontains one or moreDataTable objects, and one or more
DataRelation objects, which define relationships between the tables. You mustuse a DataAdapter to fill a DataTable in a DataSet, or to move the data it holds
back to a data source. However, there is one important exception to this
ruleDataSets can work directly with XML, which is shown directly
connected to the box on the right in Figure 23. You can load data and/or
schema directly from XML or save to XML without using a DataAdapter.
DataSet Navigation
In an ADO Recordset, you started at the beginning with the first row, and
iterated through the records one at a time. Only one row at a time could be the
current row. In a DataTable, there is no concept of the current row. It is
possible to reference rows by their ordinal position, or by a primary key or
index. Because DataSets can contain multiple related DataTables, it is also
possible to navigate master-detail relationships based on DataRelation objects.
When it is necessary to keep track of which row in a DataTable is currently
being edited in a bound Windows form, a separate CurrencyManagerobject isused.
DataTables and DataColumns
Each DataTable contains one or moreDataColumn objects. DataColumnscontain schema information, such as the data type, and whether null values are
allowed. DataColumns can have auto-incrementing functionality and can
contain expressions to automatically calculate values. In addition, you can
create event handlers that run when values in the column change.
DataRows
Each DataTable contains one or moreDataRow objects, which contain theactual data read from the data source. As with DataColumns, you can create
event handlers to respond to changes in DataRows.
8/8/2019 App Dev Ado
27/40
The ADO.NET Object Model
Understanding ADO.NET 1-25Copyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Constraints
Each DataTable has a ConstraintCollection that can contain one or more
constraints. There are two kinds of constraint objectsUniqueContraints and
ForeignKeyConstraints.
You can implement a UniqueConstraintto ensure that the data in a column (orcombination of columns) is always unique. AForeignKeyConstraintensures
that values in a column are found in another tablefor example, that the
CustomerID values in an Order table correspond to values found in the
Customers table. ForeignKeyConstraints also determine what happens when
data in a parent table is changed. For example, a ForeignKeyConstraint could
be used to automatically delete all child rows if a parent row is deleted, or to
disallow deletion of the parent record as long as related child rows exist.
DataRelations
All the data contained in DataSets is held in DataTable objects. However,DataSets are much more than mere collections of DataTable objects. As you
can see in Figure 23, each DataSet also has aDataRelationCollection, whichcontains DataRelation objects. DataRelations are distinct from Constraints in
ADO.NET. You can have relations without constraints or constraints without
relations. DataRelations are used for navigating between parent and child rows
in related tables, and to define hierarchical nesting in XML.
DataViews
There is one additional important object type not shown in Figure 23the
DataView. DataViews allow you to customize multiple views of a DataTableobject. DataViews possess additional functionality not available in aDataTable that allows you to sort, filter, and find rows in DataTables.
DataViews also allow you to specify whether rows can be added, edited, or
deleted.
XSD Schema Files and Typed DataSets
XML is used whenever a DataSet is persisted to a file or a stream for transport.
The schema for a DataSetthe tables, columns, data types, constraints, and
relationshipsis represented as XML Schema (XSD), which can be in thesame document as the XML data or in a separate document. This allows the
structure of the data to be serialized for transport or saved to disk, and
recreated later.
XSD Schema documents can also be used to create special DataSets, called
typed DataSets. These are classes derived from the generic DataSet class, with
extra code added to create properties and methods that are specific to that
particular set of tables and columns. Typed DataSets make coding easier and
they improve runtime performance.The Data Form Wizard creates a typed
8/8/2019 App Dev Ado
28/40
Introduction to ADO.NET
1-26 Understanding ADO.NETCopyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
DataSet which you can view in the designer, as shown earlier in this chapter
with the dsOrders.xsd file.
Understanding the DataAdapter
Once you populate a DataSet with data from a database by calling theFillmethod of a DataAdapter or by loading data from an XML file, you can add,
edit, and delete records in the DataSet without affecting the database or XML.
This works because the DataSet is a private cache of data that is never
connected to the source of the data. As you add, edit, or delete rows in the
DataTables of a DataSet, both the original and current values are recorded, and
the RowState of each row keeps track of whether the row has been added,
edited, or deleted.
When you want to update a database based on changes in your DataSet, you
need a separate DataAdapter for each DataTable in the DataSet. When you call
the Update method of the DataAdapter, it executes the appropriate SQL
command or stored procedures for each row that has changed, based on theRowState.
8/8/2019 App Dev Ado
29/40
The ADO.NET Object Model
Understanding ADO.NET 1-27Copyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Summary
The Data Form Wizard creates a fully-functional data-bound form.
The Data Form Wizard is a code generator, writing code to implementthe objects it creates.
A typed DataSets contains extra information about the schema, or
structure, of the data.
The DataAdapter Configuration Wizard lets you create or change a
DataAdapter object that communicates with the database.
Microsofts first object-based API for data access was DAO, which
was developed solely in relation to the Jet database engine.
RDO was added for Visual Basic developers, and ODBCDirect for
Access developers needing to access ODBC data sources.
ADO was designed as an all-purpose API capable of accessing data
stored in databases, spreadsheets, and text files, among others.
ADO.NET is based on an entirely new programming model that is
completely different from that of ADO.
ADO.NET provides scalability, interoperability, ease of programming,
and enhanced performance.
The ADO.NET architecture makes it ideal for disconnected, n-tier
applications.
System.Data.OleDb and System.Data.SqlClient are the two providers
that shipped with .NET.
The DataAdapter represents a set of data commands and a database
connection.
A DataSet contains one or more DataTable objects, and one or more
DataRelation objects, which define relationships between the tables.
Each DataTable has a ConstraintCollection that can contain one or
more constraints.
DataViews allow you to customize multiple views of a DataTable
object.
You can add, edit, and delete records in the DataSet without affecting
the database or XML.
You need a separate DataAdapter for each DataTable in the DataSet to
make changes to a database.
XML is used whenever a DataSet is persisted to a file or a stream for
transport.
XSD Schema documents are used to create typed DataSets.
8/8/2019 App Dev Ado
30/40
Introduction to ADO.NET
1-28 Understanding ADO.NETCopyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
(Review questions and answers on the following pages.)
8/8/2019 App Dev Ado
31/40
The ADO.NET Object Model
Understanding ADO.NET 1-29Copyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Questions
1. True/False: The DataForm Wizard creates a form that does not allow you
to save changes back to a database.
2. What extra information does a typed DataSet contain?
3. Which are the two data providers that shipped with .NET?
4. Which ADO.NET object represents a set of data commands and a database
connection?
5. Which object would you use to create multiple views of a DataTable?
6. What is used when a DataSet is persisted to a file or a stream for transport?
8/8/2019 App Dev Ado
32/40
Introduction to ADO.NET
1-30 Understanding ADO.NETCopyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Answers
1. True/False: The DataForm Wizard creates a form that does not allow you
to save changes back to a database.
FalseThe DataForm Wizard creates a fully-functional form.2. What extra information does a typed DataSet contain?
Information about the schema and structure of the data
3. Which are the two data providers that shipped with .NET?
System.Data.OleDb and System.Data.SqlClient
4. Which ADO.NET object represents a set of data commands and a database
connection?A DataAdapter
5. Which object would you use to create multiple views of a DataTable?A DataView
6. What is used when a DataSet is persisted to a file or a stream for transport?XML
8/8/2019 App Dev Ado
33/40
The ADO.NET Object Model
Understanding ADO.NET 1-31Copyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Lab 1:
Introduction toADO.NET
TIP: There is no completed sample for this lab.
8/8/2019 App Dev Ado
34/40
Lab 1:
Introduction to ADO.NET
1-32 Understanding ADO.NETCopyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Lab 1 Overview
In this lab youll learn how to run the Data Form Wizard and how to use the
Data Adapter Configuration Wizard.
To complete this lab, youll need to work through two exercises:
The Data Form Wizard
The Data Adapter Configuration Wizard
Each exercise includes an Objective section that describes the purpose of the
exercise. You are encouraged to try to complete the exercise from the
information given in the Objective section. If you require more information to
complete the exercise, the Objective section is followed by detailed step-by-
step instructions.
8/8/2019 App Dev Ado
35/40
The Data Form Wizard
Understanding ADO.NET 1-33Copyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
The Data Form Wizard
ObjectiveIn this exercise, youll use the Data Form Wizard to create a form based on the
Categories and Products tables in the Northwind SQL Server database.
Things to Consider
How do you launch the Data Form Wizard?
Step-by-Step Instructions
1. Open the IntroLab.sln file.
2. Right-clickon the IntroLab project in the Solution Explorer window
and choose Add|Add New Item from the menu.
3. Select Data Form Wizard. Name the form frmProducts.vb and click
Open to launch the wizard.
4. ClickNext to bypass the introductory screen. Select the Create a new
dataset named option and name it dsProducts. ClickNext.
8/8/2019 App Dev Ado
36/40
Lab 1:
Introduction to ADO.NET
1-34 Understanding ADO.NETCopyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
5. If you do not have an existing connection to the Northwind SQL
Server database, clickNew Connection. Fill in the Data Link
properties as shown in Figure 25. ClickOKand then Next.
Figure 25. Fill in the Data Link Properties dialog box to connect to your localcopy of the Northwind database.
6. Select the Categories and Products tables by moving them to the
right-hand pane. ClickNext.
7. Create a relationship and name it relCatProducts. Select Categoriesfrom the Parent table drop-down list, and select Products from the
Child table drop-down list. Select CategoryId in the second drop-
down list under both Parent table and Child table. This is the
primary/foreign key relationship between Categories and Products.
This reflects the relationship between the two tables in the Northwinddatabase. Click the wedgie button (>) to add the relation to the
Relations box on the right side of the dialog box. This removes all of
your selections in the drop-down list boxes and you will see only the
relCatProducts name in the Relations pane. ClickNext.
8/8/2019 App Dev Ado
37/40
The Data Form Wizard
Understanding ADO.NET 1-35Copyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
8. Clear the Description check box as shown in Figure 26 and click
Next.
Figure 26. Clearing the Description check box will cause the Description to not
show up on the final form.
9. Select the Single record in individual controls option and leave all of
the other check boxes checked. ClickFinish.
10. Note that two items have been added to the Solution Explorer, as
shown in Figure 27.
Figure 27. The dsProducts.xsd and the frmProducts.vb files have been added to
the project by the Data Form Wizard.
11. Right-click on the IntroLab project and choose Properties. Select
frmProducts from the Startup object drop-down list. ClickOK.
12. Press F5 to run the project. Test the form and make sure that its
working properly.
8/8/2019 App Dev Ado
38/40
Lab 1:
Introduction to ADO.NET
1-36 Understanding ADO.NETCopyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
13. If you have time, take a look and explore the code that the wizard
generated.
8/8/2019 App Dev Ado
39/40
The Data Adapter Configuration Wizard
Understanding ADO.NET 1-37Copyright by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
The Data Adapter ConfigurationWizard
Objective
In this exercise, youll run the Data Adapter Configuration Wizard to revise
the original query that selected all of the records from the Products table so
that it does not display discontinued products.
Things to Consider
How do you launch the Data Adapter Configuration Wizard?
How do you revise the existing query?
Step-by-Step Instructions
1. Open frmProducts in the designer if it is not already open. You will
notice that there are two OleDbDataAdapter objects in the well.
2. Right-clickon OleDbDataAdapter2 and choose Configure Data
Adapter from the menu. When the wizard launches, click the Next
button to bypass the introductory screen.
3. In the Choose Your Data Connection dialog box, select the
connection you used in Exercise 1 from the drop-down list box and
clickNext.
4. In the Choose a Query Type dialog box, choose Use SQL statements
and clickNext.
8/8/2019 App Dev Ado
40/40
Lab 1:
Introduction to ADO.NET
5. In the Generate the SQL Statements dialog box, click the Query
Builder button. In the Criteria column, type the expression =0. Clear
the check box in the Products column list. The Query Builder window
should look like Figure 28. ClickOK.
Figure 28. Setting a criteria to only display products that have not been
discontinued.
6. ClickNext and then Finish.
7. To test your changes, press F5 to run the project. Discontinuedproducts will no longer be displayed.