You are on page 1of 49

ADO.

NET
Objectives
 Introduce Microsoft® ADO.NET
 Show the evolution of ADO to ADO.NET
 Introduce the primary components of ADO.NET
Contents
 Differences Between ADO and ADO.NET
 Benefits of ADO.NET
 ADO.NET Core Concepts and Architecture
 The ADO.NET Object Model
 The DataSet and Data Views
 Managed Providers
ADO.NET and the .NET Framework

Microsoft .NET Framework

Web Services User Interface

Data and XML


ADO.NET XML ... ...

Base Classes

Common Language Runtime


ADO vs. ADO.NET 1/2
 ADO
 Designed for connected access
 Tied to the physical data model
 The RecordSet is the central data container
 RecordSet is one (1) table that contains all the data
 Retrieving data from > 1 table or source requires a database JOIN
 Data is “flattened”: lose relationships; navigation is sequential
 Data types are bound to COM/COM+ data types
 Data sharing via COM marshalling
 Problems marshalling through firewalls (DCOM, binary)
ADO vs. ADO.NET 2/2
 ADO.NET
 Designed for disconnected access
 Can model data logically!
 The DataSet replaces the RecordSet
 DataSet can contain multiple tables
 Retrieving data from > 1 table or source does not require a JOIN
 Relationships are preserved: navigation is relational
 Data types are only bound to XML schema
 No data type conversions required
 XML, like HTML, is plaintext: “Firewall friendly”
Benefits of ADO.NET
 Interoperability through use of XML (more later!)
 Open standard
 Human readable and decipherable text
 Data describes itself—that’s XML
 Used to transfer all data in ADO.NET
 Scalability through the disconnected DataSet
 Connections are not maintained for long periods
 Database locking does not occur
 Works the way the Web works: “Hit and Run!”
 Maintainability
 Separation of data logic and user interface
Visual Studio.NET Enhancements
 Programmability
 Typed programming—a programming style
 Uses end-user words: Easier to read and write
 Statement completion in Microsoft Visual Studio.NET
 Safer: Provides compile-time checking
 Examples:
 Untyped:
Table("Customer")("Jones").Column(“Balance”)
 Typed:
myDataSet.Customer("Jones").Balance
 Wizard support for queries
Core Concepts and Architecture
 The ADO.NET Object Model
 DataSet objects
 Managed providers
 ADO.NET-related Namespaces
 System.Data
 System.Data.ADO
 System.Data.Internal
 System.Data.SQL
 System.Data.SQLTypes
ADO.NET-related Namespaces

ADO.NET

System.Data

.SQLTypes .SQL .Internal .ADO


The ADO.NET Object Model
 DataSet

 Managed Providers
System.Data 1/2

 Contains the basis and bulk of ADO.NET


 Data-centric namespace
 Provides the means to work on and with your data!
 Classes and methods to manipulate your data
 Ability to create views of your data
 Means to logically represent your data
 Enables the use of XML to view, share, and store data
System.Data 2/2

System.Data  Contains the “main” classes of ADO.NET


DataSet  In-memory cache of data
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 2 DataTables to each other
DataSetView  Used to create a view on a DataSet
System.Data and DataSet—Overview

DataSet Tables
DataTable DataView
DataRow(s)

Relations DataColumn

DataRelation Constraint(s) DataSetView


DataRelation
DataTable

DataTable
System.Data—DataSet 1/3
 An in-memory cache of data from a data source
 Common way to represent and manipulate data
 Universal data container
 Not just for use with databases
 Logical or physical representation of data; depends on:
 The query/result set
 Whether DataTables and Relations exist
 Designed to be disconnected from the data source
 Connect, execute query, disconnect
 XML used to read and write data and schema
System.Data—DataSet 2/3
 Collections are used to add & remove tables & relations
 Properties of Interest:
 Tables: Returns the collection of DataTable objects
 Relations: Returns the collection of DataRelations
 XML: Gets or sets the definition of the DataSet as XML
 XMLData: Gets or sets the DataSet’s data as XML
 XMLSchema: Gets or sets the DataSet schema as XML
 Namespace: Gets or sets the namespace of the DataSet
 Using Properties Sample:
 aTableCollection=aDS.Tables.Add(aTable);
System.Data—DataSet 3/3

Universal Data Container

DataSet: It’s not just for Databases


System.Data—DataTable
 May be mapped to a physical table in the data source
 Can be related to one another through DataRelations
 Optimistic concurrency or locking - model
 Properties of Interest:
 Columns: Returns ColumnsCollection of DataColumns
 Rows: Returns DataRow objects as a RowsCollection
 ParentRelations: Returns the RelationsCollection
 Constraints: Returns the table’s ConstraintsCollection
 DataSet: Returns the DataSet of the DataTable
 PrimaryKey: Gets the DataColumns that make up the
table’s primary key
System.Data—DataSet and DataTable
 Create a DataTable and add it to a DataSet

DataSet ds = new DataSet();

// Create DataTable object: “Customers”.


DataTable dt= new DataTable( “Customers” );

// Create and add columns to the table


// 1. Explicitly create and Add a DataColumn
DataColumn dc = new DataColumn( “CustID”, Int16 );
dt.Columns.Add( dc );

// 2. Implicitly Create and Add columns (DataColumn).


dt.Columns.Add( “First_Name”, String );
dt.Columns.Add( “Last_Name”, String );

// Add the DataTable object to the DataSet


ds.Tables.Add( dt );
System.Data—DataRelation 1/2
 Used to create logical relations
 Create relations between two (2) DataTable objects
 Requires a DataColumn object from each DataTable
 The DataType of both DataColumns must be the same
 Cannot relate a Int32 DataColumn and a String DataColumn
 The relation is named (by you!)
 DataRelation dr=new DataRelation( “myRelation”,...)

 Makes relational navigation possible


 RelationsCollection contains all the DataRelations
 Accessed through the DataSet’s Relations property
System.Data—DataRelation 2/2
 How to create a DataRelation:
 Get the DataColumn objects to relate
 Create a named DataRelation using the columns
 Add the relation to the DataSet

// Building on the DataTable example earlier...


// Get the DataTable DataColumns we need to relate...
DataColumn parentCol, childCol;
parentCol= DataSet.Tables["Customers"].Columns["CustID"];
childCol = DataSet.Tables["Orders“].Columns["CustID"];

// Create DataRelation with the name “CustomerOrders”...


DataRelation dr;
dr = New DataRelation("CustomersOrders", parentCol,

childCol);
// Add the relation to the DataSet...
ds.Relations.Add( dr );
System.Data—DataSet and XML
 DataSet can read/write XML for its data and/or schema
 Means: You can create or modify a DataSet using XML!
 XML-related DataSet methods for reading:
 ReadXml: Reads an XML schema and data into the DataSet
 ReadXmlData: Reads XML data into the DataSet
 ReadXmlSchema: Reads an XML schema into the DataSet
 And for writing: WriteXml, WriteXmlData, WriteXmlSchema
 XML-related properties:
 Xml, XmlData, XmlSchema, and Namespace
 DiffGrams
Methods of Reading and Writing XML
// Code for creating the DataSet mds and loading the
// DataSet from a data source not shown.

String oFile = “C:\\My_ADO.NET\\myXmlOutput.xsd”;


String iFile = “C:\\My_ADO.NET\\myXmlInput.xsd”;

// Write the DataSet’s XMLSchema to an XML Document


mds.WriteXmlSchema( oFile );

// Read/Upload XML Data into the DataSet


mds.ReadXmlData( iFile, true );

// Write the existing Data to an XML Document


mds.WriteXmlSchema( “C:\\My_ADO.NET\\myXmlData.txt );

// Or output the XML Data using the XmlData property!


Console.WriteLine( mds.XmlData );
System.Data—DataView
 Create multiple views on DataTable objects
 Bindable to user interface controls
 Properties of Interest:
 Item: Retrieves a row of data from a specified table
 Table: Retrieves or sets the associated DataTable
 Sort: Gets or sets the table’s sort columns and sort order
 RowFilter: Gets or sets the expression used to filter rows
 RowStateFilter: Gets or sets the row state filter
 None, Unchanged, New, Deleted, ModifiedCurrent, and others
System.Data—DataView Sample
 Creating DataView objects
// Code for myTable “Customers” with
// “Name” column not shown
DataView view1 = new DataView( myTable );
DataView view2 = new DataView( myTable );

// Creates Ascending view of Customers by “Name”


view1.Sort = “Name ASC”;

// Set the view to show only modified (original) rows


view2.RowStateFilter= DataViewRowState.ModifiedOriginal;

// Bind to UI element(s)...
DataGrid myGrid = new DataGrid();
myGrid.SetDataBinding( view1, “Customer”);

//...
System.Data—DataSetView
 Similar to a DataView but DataSet oriented
 Used to create multiple views on a DataSet
 Ability to automatically set filters on the tables
 Properties of Interest:
 TableSettings: Gets/sets the view settings on tables
 DataSet: Gets or Sets the DataSet to be viewed
System.Data—DataSetView Sample
 Creating DataSetView object using a DataSet
// Create the views...
DataSetView dsView1 = new DataSetView( myDS );

// Create TableSetting objects...


TableSetting ts1, ts2 ;
ts1 = new TableSetting( myDS.Tables[“Orders”],
“CustID”, “CustID<100”,
DataViewRowState.CurrentRows );
ts2 = new TableSetting( myDS.Tables[“Orders”],
“ProductId”, “ProductId>1011”,
DataViewRowState.CurrentRows );

// Add TableSettings to the DataSetView...


dsView.TableSettings.Add( ts1 );
dsView.TableSettings.Add( ts2 );

// Bind to a UI element/control...
DataSet, DataRelation, Data…Views

DataSet Tables
DataView

DataTable
DataSetView
DataRow(s)
TableSettings
DataColumn
Relations TableSetting
Constraint(s)
DataRelation TableSetting
DataRelation DataTable

DataTable
ADO.NET and Managed Providers
A collection of classes for accessing data sources:
 Microsoft SQL Server™ 2000, SQL Server 7, and MSDE
 Any OLE Database (OLE DB) providers
 Including: Oracle, JET, and SQL OLE DB Providers
 Establish connection between DataSets and data stores
 Two managed providers:
 ADO: via the System.Data.ADO namespace
 SQL Server: via the System.Data.SQL namespace
 System.Data.ADO is the ADO.NET managed provider
System.Data—Managed Providers

System.Data
.SQL .ADO
SQLCommand ADOCommand
SQLConnection ADOConnection
SQLDataReader ADODataReader
SQLDataSetCommand ADODataSetCommand

 Rely on System.Data.Internal for various inherited classes


ADOConnection and SQLConnection
 Represent a unique session with a data source
 Create, open, close a connection to a data source
 Functionality and methods to perform transactions
 ADOConnection example:
String conStr="Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=NWIND_RW.MDB";
ADOConnection aConn = new ADOConnection(conStr);
aConn.Open();
// Execute Queries using ADODataSetCommand Class
aConn.Close();
ADODataSetCommand Class 1/2

 Bridge between the DataSet and the data store


 Inherited from the DataSetCommand class
 Means to modify the DataSet and data source

Data Store DataSetCommand DataSet


ADODataSetCommand Class 2/2
 Properties of Interest:
 DeleteCommand: The delete command expressed in SQL
 InsertCommand: Gets or sets insert command
 SelectCommand: Gets or sets select command
 UpdateCommand: Gets or sets update command
 TableMappings: Maps source and DataTable
 ADOCommands retrieved or set by “command” properties
 Inherits methods from DataSetCommand class
 public virtual int FillDataSet( DataSet dataSet );
 public virtual int Update( DataSet dataSet );
ADOCommand Class

 Represents a query to execute on the data source


 Properties of Interest:
 ActiveConnection: Get or set the data source connection
 CommandText: Get or set the query (text) command
 CommandType: Get or set interpretation of command text
 Text, stored procedure, or table name
 CommandTimeout: The seconds until connection timeout
 RecordsAffected: Number of records affected by query
ADODataReader 1/2

 Forward-only data access


 “Lightweight” programming model
 Less overhead than using ADODataSetCommand
 Instantiated by the ADOCommand class Execute method
 Ties up the ADOCommand until it is finished reading
ADODataReader 2/2

 Properties of Interest:
 FieldCount: Returns the number of fields in the result set
 HasMoreRows: Indicates if there are more rows to retrieve
 RowFetchCount: Number of rows to retrieve at one time
 HasMoreResults: Indicates that more results exist
 Methods to retrieve data:
 By column type and index: GetString, GetInt32, and so on
 Read: Advances reader to next record
ADODataReader Sample
// Code for creating the ADOConnection “adoConn” not shown
String myQuery = “SELECT * FROM Customers”;
adoConn.Open();
ADOCommand myCmd = new ADOCommand( myQuery,adoConn );

// Declare the ADODataReader...


ADODataReader myDataReader;

// Instantiate the ADODataReader with Execute(...) ...


myCmd.Execute(out myDataReader);

// Always call Read before accessing data.


while(myDataReader.Read())
{
Console.WriteLine(myDataReader.GetString(0));
}

// Always Close the reader and the connection when done


myDataReader.Close();
adoConn.Close();
Summary
 ADO.NET is the evolution of ADO
 It is a disconnected, Web-centric model
 Flexible in its ability to work with data
 Increases your ability to logically organize data
 Extensive support for XML
 Facilitates working with and sharing data
 Interacts with a wide variety of data sources
Questions ?
Duwamish Books
A Sample Application for Microsoft .NET
Installing the Sample 1/2
 Install the "Enterprise Samples" with Visual Studio.NET
 Location of the C# Version
 Visual Studio.NET folder
 Directory .\EnterpriseSamples\DuwamishOnline CS
 Location of the Visual Basic® Version
 Directory .\EnterpriseSamples\DuwamishOnline VB
 Installation Tasks
 Check the prerequsites
 Microsoft Windows® 2000 Server, SQL Server 2000 with English
Query optional and supported
 Read the Readme.htm
 Run Installer Duwamish.msi (double-click it)
Installing the Sample 2/2
 The installation wizard will guide you
 Defaults should be OK for almost everybody
 Setup will install database, Web site, and code
 After installation is complete:
 File/Open Solution with the Duwamish.sln file
 Can build the sample with Build/Build Solution
Duwamish Architecture Overview
User / Browser
ASP.NET

IIS

Web
SystemFramework

Common.Data
BusinessFacade

BusinessRules

DataAccess

ADO.NE
T Database
Common Components
 Duwamish7.Common
 Contains systems configuration options
 Contains common data definitions (classes)
 Namespace Duwamish.Common.Data
 "Internal" data representation for Book, Category,
Customer, OrderData
 Duwamish7.SystemFramework
 Diagnostics utilities
 Pre and post condition checking classes
 Dynamic configuration
 In short:
 Everything that's pure tech and not business code
Duwamish7.DataAccess
 Contains all database-related code
 Uses ADO.NET architecture
 Using SQL Server managed provider
 Shows DataSet, DataSetCommand usage
 Optimized for performance by using stored procs
Duwamish7.BusinessRules
 Implements all business rules
 Validation of business objects (for example,
Customer EMail)
 Updating business objects
 Calculations (Shipping Cost, Taxes)
 All data access performed through DataAccess
Duwamish7.BusinessFacade
 Implements logical business subsystems
 CustomerSystem: Profile management
 OrderSystem: Order management
 ProductSystem: Catalog
 Reads data through DataAccess
 Data validated and updated using BusinessRules
 BusinessFacade encapsulates all business-related
functionality
Duwamish7.Web
 Implements the user interface for Web access
 Uses ASP.NET architecture
 Employs Web Forms model
 Uses code behind forms
 Manages state
 Uses custom Web Controls
 All functionality accessed through BusinessFacade
Shop at Duwamish Online.NET
 Demo: Duwamish in Action

You might also like