Sample Chapter : All Rights Reserved. Reproduction Is Strictly Prohibited
Sample Chapter : All Rights Reserved. Reproduction Is Strictly Prohibited
NET
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.
Understanding ADO.NET
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Introduction to ADO.NET
Welcome and thank you for choosing Application Developers Training Company (AppDev) to
guide you through an in-depth exploration of the powerful features of Microsoft ADO.NET.
The key to a successful learning experience is comprehensive courseware that you can easily
understand and apply to your work environment quickly. We are sure you will find our courseware
invaluable 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 most
effective and comprehensive training in North America for Microsoft .NET, Access, Active Server
Pages, Visual Basic, VBA, Visual FoxPro, Visual InterDev, SQL Server, Developing Applications
with Access and SQL Server, and XML. Our instructors are practicing developers who are
recognized experts, successful authors, sought after speakers, and experienced trainers of
application 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 master ADO.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 can’t
find 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 to
teach courseware specifically tailored to your organization’s needs.
We hope you find today’s 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 excellent
development product. If you have any questions or comments about this course or other training
that we offer, please don’t hesitate to call us at 1-800-578-2062. You can also visit our Web site at
http://www.appdev.com where you can view course schedules, outlines and descriptions, or even
look over some sample courseware.
Understanding ADO.NET
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Introduction to ADO.NET
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
See frmWizard in The following demonstration walks you through the steps of using the Data
Intro.sln 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:
2. Select Data Form Wizard, as shown in Figure 1. Name the form and
click Open. This launches the wizard.
3. Click Next 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. Click Next.
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.
Click OK in the dialog box, and click Next in the wizard.
5. Select the Orders and Order Details tables by moving them to the
right-hand pane shown in Figure 4, and click Next.
6. Since there’s 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.
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. Click Next.
8. You then need to specify which columns you’d like displayed on the
form. If you don’t 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. Click Next.
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. Don’t 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. Click Finish.
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.
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).
If you play with the form, you’ll find that all of the controls work. However,
it’s 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, you’d want to put in
some state management for the form and more robust error handling.
See frmWizard.vb One thing that sets data binding in .NET apart from data binding in earlier
technologies 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. Don’t worry about the details for
nowyou’ll have a chance to explore the ADO objects used later on.
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.
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.
The DataSet
See dsOrders.xsd 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.
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.
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
structure, of the data, allowing them to run more efficiently and to be easier to
work with in code.
See frmWizard If you look at frmWizard in the designer, you’ll 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.
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. Click Next.
3. The following wizard dialog box, shown in Figure 17, allows you to
choose from the following options: Use SQL statements, Create new
stored procedures, or Use 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. Click Next.
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.
If you’ve 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 you’re 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.
ODBC
Microsoft’s first technology for providing generic data access was ODBC
(Open Database Connectivity). ODBC has been very successful, but it is
difficult 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
Microsoft’s 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.
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.
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.
• Scalability
• Interoperability
• Ease of programming
• Performance
Scalability
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.
Performance
The DataAdapter
The DataAdapter represents a set of data commands and a database
connection. 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 Fill method to execute
the SelectCommand to 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 you
to open and close connections, which are pooled automatically and can be
made part of transactions.
Each data provider contains its own specialized versions of these classes. In
reality there is no DataAdapter objectonly a SqlDataAdapter, an
OleDbDataAdapter, etc. The same specialization and naming applies to the
Connection, Command, Parameter, and DataReader objects.
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 it’s more work, it is more efficient to create
your ADO.NET objects by hand, which you’ll 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.
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.
DataRows
Each DataTable contains one or more DataRow objects, which contain the
actual data read from the data source. As with DataColumns, you can create
event handlers to respond to changes in DataRows.
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 UniqueConstraint to ensure that the data in a column (or
combination of columns) is always unique. A ForeignKeyConstraint ensures
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 a DataRelationCollection, which
contains 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 DataTable
object. DataViews possess additional functionality not available in a
DataTable 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 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
DataSet which you can view in the designer, as shown earlier in this chapter
with the dsOrders.xsd file.
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 the
RowState.
Summary
• The Data Form Wizard creates a fully-functional data-bound form.
• The Data Form Wizard is a code generator, writing code to implement
the 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.
• Microsoft’s 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.
Questions
1. True/False: The DataForm Wizard creates a form that does not allow you
to save changes back to a database.
3. Which are the two data providers that shipped with .NET?
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.
3. Which are the two data providers that shipped with .NET?
System.Data.OleDb and System.Data.SqlClient
Lab 1:
Introduction to
ADO.NET
TIP: There is no completed sample for this lab.
Lab 1 Overview
In this lab you’ll learn how to run the Data Form Wizard and how to use the
Data Adapter Configuration Wizard.
Objective
In this exercise, you’ll 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.
3. Select Data Form Wizard. Name the form frmProducts.vb and click
Open to launch the wizard.
4. Click Next to bypass the introductory screen. Select the Create a new
dataset named option and name it dsProducts. Click Next.
Figure 25. Fill in the Data Link Properties dialog box to connect to your local
copy of the Northwind database.
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. Click Finish.
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.
12. Press F5 to run the project. Test the form and make sure that it’s
working properly.
Objective
In this exercise, you’ll 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.
4. In the Choose a Query Type dialog box, choose Use SQL statements
and click Next.
Figure 28. Setting a criteria to only display products that have not been
discontinued.