Académique Documents
Professionnel Documents
Culture Documents
NET
Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation. Microsoft, MS-DOS, Windows, Visual C#, Visual Basic, Visual C++, Visual Studio, and Win32 are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. 2002 Microsoft Corporation. All rights reserved. Version 1.0 The names of actual companies and products mentioned herein may be the trademarks of their respective owners.
Contents
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 What Does the Data Access Application Block Include? . . . . . . . . . . . . . . . . . . . . . . . 3 The Visual Studio .NET Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 The Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 System Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 Downloading and Installing the Data Access Application Block . . . . . . . . . . . . . . . . . . 5 Using the Data Access Application Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Executing Commands with the SqlHelper Class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 Managing Parameters with the SqlHelperParameterCache Class . . . . . . . . . . . . . . . . 9 Internal Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 SqlHelper Class Implementation Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 SqlHelperParameterCache Class Implementation Details . . . . . . . . . . . . . . . . . . . . 13 Frequently Asked Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Feedback and Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 More Information. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 Collaborators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Introduction
Are you involved in the design and development of data access code for .NET applications? Have you ever felt that you write the same data access code again and again? Have you wrapped data access code in helper functions that let you call a stored procedure in one line? If so, the Microsoft Data Access Application Block for .NET is for you. The Data Access Application Block encapsulates performance and resource management best practices for accessing Microsoft SQL Server databases. It can easily be used as a building block in your own .NET application. If you use it, you will reduce the amount of custom code you need to create, test, and maintain. Specifically, the Data Access Application Block helps you: Call stored procedures or SQL text commands. Specify parameter details. Return SqlDataReader, DataSet, or XmlReader objects. For example, in an application that references the Data Access Application Block, you can call a stored procedure and generate a DataSet in a single line of code, as follows:
[Visual Basic] Dim ds As DataSet = SqlHelper.ExecuteDataset( _ connectionString, _ CommandType.StoredProcedure, _ "getProductsByCategory", _ new SqlParameter("@CategoryID", categoryID)) [C#] DataSet ds = SqlHelper.ExecuteDataset( connectionString, CommandType.StoredProcedure, "getProductsByCategory", new SqlParameter("@CategoryID", categoryID));
Note: This Application Block for .NET design is based on reviews of successful .NET applications. It is provided as source code that you can use as-is or customized for your application. It is not an indication of future direction for Microsoft ADO.NET libraries, which are built for fine-grained control of data access behavior in a wide range of use cases. Future releases of ADO.NET may address this scenario with a different model.
The remainder of this overview is divided into the following sections: What Does the Data Access Application Block Include? Downloading and Installing the Data Access Application Block Using the Data Access Application Block Internal Design Frequently Asked Questions Feedback and Support Collaborators
The Documentation
The documentation for the Data Access Application Block includes the following main sections: Developing Applications with the Data Access Application Block. This section includes quick start samples, covering a range of common use cases which helps you start to use the Data Access Application Block quickly and easily. Design and Implementation of the Data Access Application Block. This section includes background design philosophy information that provides insights into the design and implementation of the Data Access Application Block. Deployment and Operations. This section includes installation information that includes deployment and update options, as well as security related information. Reference. This is a comprehensive API reference section that details the classes and interfaces comprising the Data Access Application Block.
System Requirements
To run the Data Access Application Block, you need the following: Microsoft Windows 2000, Windows XP Professional The RTM version of the .NET Framework SDK (available for downloading at http://msdn.microsoft.com/downloads/default.asp?url=/downloads/sample.asp?url =/msdn-files/027/000/976/msdncompositedoc.xml&frame=true) The RTM version of Visual Studio .NET (recommended but not required) A SQL Server 7.0 or later database server
SqlHelper
ExecuteNonQuery T-SQL Statement or Stored Procedure ExecuteDataset ExecuteReader int DataSet SqlDataReader object XmlReader CacheParameterSet GetCachedParameterSet SqlParameter Array GetSpParameterSet ExecuteScalar ExecuteXmlReader SqlHelperParameterCache
Figure 1
Data Access Application Block
The SqlHelper class provides a set of static methods that you can use to execute a variety of different command types against a SQL Server database. The SqlHelperParameterCache class provides command parameter caching functionality used to improve performance. This is used internally by a number of the Execute methods (specifically, the overrides that are designed to execute only stored procedures). It can also be used directly by the data access client to cache specific parameter sets for specific commands.
In addition to these overloads, all methods other than ExecuteXmlReader provide overloads to allow connection information to be passed as a connection string, rather than as a connection object, as shown in the following method signatures:
[Visual Basic] Execute* (ByVal connectionString As String, ByVal commandType As CommandType, _ ByVal commandText As String) Execute* (ByVal connectionString As String, ByVal commandType As CommandType, _ ByVal commandText As String, _ ByVal ParamArray commandParameters() As SqlParameter) Execute* (ByVal connectionString As String, ByVal spName As String, _ ByVal ParamArray parameterValues() As Object) [C#] Execute* (string connectionString, CommandType commandType, string commandText) Execute* (string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters) Execute* (string connectionString, string spName, params object[] parameterValues)
Note: The ExecuteXmlReader does not support a connection string because, unlike SqlDataReader objects, an XmlReader object does not provide a way to close connections automatically when the XmlReader is closed. Clients that passed a connection string would have no way of closing the connection object associated with the XmlReader when they had finished with it.
You can write code that uses any of the SqlHelper class methods simply by referencing the Data Access Application Block assembly and importing the Microsoft.ApplicationBlocks.Data namespace, as illustrated in the following code sample.
[Visual Basic] Imports Microsoft.ApplicationBlocks.Data [C#] using Microsoft.ApplicationBlocks.Data;
After the namespace has been imported, you can call any of the Execute* methods, as illustrated in the following code sample.
[Visual Basic] Dim ds As DataSet = SqlHelper.ExecuteDataset( _ "SERVER=(local);DATABASE=Northwind;INTEGRATED SECURITY=True;", _ CommandType.Text, "SELECT * FROM Products")
The following code shows how parameters for a Transact-SQL statement can be cached and retrieved by using the SqlHelperParameterCache class.
[Visual Basic] 'Initialize the connection string and command text 'These will form the key used to store and retrieve the parameters Const CONN_STRING As String = _ "SERVER=(local); DATABASE=Northwind; INTEGRATED SECURITY=True;" Dim sql As String = _ "SELECT ProductName FROM Products WHERE Category=@Cat AND SupplierID = @Sup"
(continued)
10
(continued)
'Cache the parameters Dim paramsToStore(1) As SqlParameter paramsToStore(0) = New SqlParameter("@Cat", SqlDbType.Int) paramsToStore(1) = New SqlParameter("@Sup", SqlDbType.Int) SqlHelperParameterCache.CacheParameterSet(CONN_STRING, sql, paramsToStore) 'Retrieve the parameters from the cache Dim storedParams(1) As SqlParameter storedParams = SqlHelperParameterCache.GetCachedParameterSet(CONN_STRING, sql) storedParams(0).Value = 2 storedParams(1).Value = 3 'Use the parameters in a command Dim ds As DataSet ds = SqlHelper.ExecuteDataset(CONN_STRING, CommandType.Text, sql, storedParams) [C#] // Initialize the connection string and command text // These will form the key used to store and retrieve the parameters const string CONN_STRING = "SERVER=(local); DATABASE=Northwind; INTEGRATED SECURITY=True;"; string spName = "SELECT ProductName FROM Products WHERE Category=@Cat AND SupplierID = @Sup"; //Cache the parameters SqlParameter[] paramsToStore = new SqlParameter[2]; paramsToStore[0] = New SqlParameter("@Cat", SqlDbType.Int); paramsToStore[1] = New SqlParameter("@Sup", SqlDbType.Int); SqlHelperParameterCache.CacheParameterSet(CONN_STRING, sql, paramsToStore); //Retrieve the parameters from the cache SqlParameter storedParams = new SqlParameter[2]; storedParams = SqlHelperParameterCache.GetCachedParameterSet(CONN_STRING, sql); storedParams(0).Value = 2; storedParams(1).Value = 3; //Use the parameters in a command DataSet ds; ds = SqlHelper.ExecuteDataset(CONN_STRING, CommandType.StoredProcedure, sql, storedParams);
11
Internal Design
The Data Access Application Block includes the full source code and a comprehensive guide to its design. In this section, the main implementation details are described.
Internal Design
13
In addition to the public methods, the SqlHelper class includes a number of private functions, which are used to manage parameters and prepare commands for execution. Regardless of the method implementation called by the client, all commands are executed by using a SqlCommand object. Before this SqlCommand object can be executed, any parameters must be added to its Parameters collection, and the Connection, CommandType, CommandText, and Transaction properties must be set appropriately. The private functions in the SqlHelper class are primarily designed to provide a consistent way to execute commands against a SQL Server database, regardless of the overloaded method implementation called by the client application. The private utility functions in the SqlHelper class are: AttachParameters: A function used to attach any necessary SqlParameter objects to the SqlCommand being executed. AssignParameterValues: A function used to assign values to the SqlParameter objects. PrepareCommand: A function used to initialize the properties of the command, such as its connection, transaction context, and so on. ExecuteReader: This private implementation of ExecuteReader is used to open a SqlDataReader object with the appropriate CommandBehavior in order to manage the lifetime of the connection associated with the reader most efficiently.
Can I use XCOPY deployment to deploy the Data Access Application Block assemblies?
Yes. After it is compiled, the Microsoft,ApplicationBlocks.Data.dll assembly can be XCOPY deployed.
When should I use the ExecuteDataset method and when should I use the ExecuteReader method?
The real question here is when should you return multiple rows of data in a DataSet object, and when should you use a DataReader. The answer depends on the needs of your particular application and your priorities in terms of flexibility versus raw performance. DataSets give you a flexible, disconnected, relational view of your data while DataReaders provide an extremely high performance, read only, forward only cursor. For a comprehensive comparison of DataSets and DataReaders, see the Data Access Architecture Guide.
15
For example, suppose you have the following stored procedures in your database.
CREATE AS SELECT GO CREATE AS SELECT PROCEDURE GetCategories * FROM Categories PROCEDURE GetProducts * FROM Products
You could create a master stored procedure that makes nested calls to these procedures, as illustrated in the following code sample.
CREATE PROCEDURE GetCategoriesAndProducts AS BEGIN EXEC GetCategories EXEC GetProducts END
Executing this master stored procedure with the ExecuteDataset method returns a single DataSet containing two tables; one containing the category data and the other containing the product data.
Note: The ExecuteDataset method does not provide a way to assign custom names to the tables returned. The first table is always numbered 0 and named Table, the second is numbered 1 and named Table1, and so on.
More Information
The Data Access Application Block is designed and developed based on the best practices and general design principles discussed in the Data Access in .NET Architecture Guide. Read this guide to learn more about data access.
Collaborators
Many thanks to the following contributors and reviewers: Susan Warren, Brad Abrams, Andy Dunn, Michael Day, Mark Ashton, Gregory Leake, Steve Busby, Kenny Jones, David Schleifer, Andrew Roubin (Vorsite Corp.), Jeffrey Richter (Wintellect), Bernard Chen (Sapient), and Matt Drucker (Turner Broadcasting). Thanks, also, to the content team: Tina Burden (Entirenet), Shylender Ramamurthy (Infosys Technologies Ltd), and Filiberto Selvas Patino.