ArticleDirectory
- 2.1.1-source mode of data access application blocks
This document is maintained in: http://wiki.entlib.net.cn/EntlibHelp31DataAccessApplicationBlock.ashx.
This topic describes how to use data to access an applicationProgramBlock development applications. First explains how to configure the Application Block and add it to the application. Then, in key scenarios, explains how to use application blocks in specific scenarios, such as getting a single item or usingDatasetObject To obtain multiple rows. Finally, we provide more information about connection management, parameter processing, and Exception Handling in any development details. This topic assumes that the original application block is used, that is, there is no extension. (To learn how to add features, see extend and modify data access application blocks .)
All application blocks areSource codeFor release, you must compile before using the Quick Start and configuration console. Learn how to compile the Enterprise Library SourceCodeFor more information, see build an Enterprise Library.
2.1-enter configuration information
The following process shows how to configure data access application blocks.
This process explains how to configure data access application blocks. The attributes associated with the node are displayed on the right panel.
Add a Data Access Application Block
- Open the configuration file. For more information, configure the Application Block parameters.
- Right-clickApplication configuration, PointingNewAnd then clickData Access Application Block.
The next process explains how to configure the default database instance.Databasefactory. createdatabaseMethod.
Configure the default database
- In the right pane, expandDefaultdatabaseAttribute.
- IsDefaultdatabaseEnter the name of the connection string or select it from the drop-down list. The default connection string name is connectionstring.
- (Optional) enter a new name for design.NameAttribute. The default name isConnectionstring.
- InProvidernameAttribute section. If you want to, you may modify the name of the provider. Enter the provider name or select it from the drop-down list. The default provider name isSystem. Data. sqlclient.ProvidernameThe property must beDbproviderfactoryThe name of the provider specified in the class.
The next process explains how to create a connection string for a named database instance. When the configuration console saves the connection string, it generates a semicolon-separated string that saves value pairs in name = value format. For example, if you use the configuration console to generate a connection string by default, the configuration console generates the following connection strings.
Database = database; server = (local) "sqlexpress; Integrated Security = sspi;
Configure the connection string
- ClickConnectionstringNode.
- (Optional) enter a new name to setNameAttribute, which isConnectionstringThe name of the node. The default name isConnectionstring.
- (Optional)ProvidernameAttribute section to modify the name of the provider. Enter the provider name or select it from the drop-down list. The default provider name isSystem. Data. sqlclient.ProvidernameThe attribute must be specified inDbproviderfactoryThe name of the provider in the class.
- Update with the following valuesConnectionstringAttribute.
Database = database; server = (local) "sqlexpress; Integrated Security = sspi
The next process shows how to configure an SQL Server ce database. These steps are appropriate if the application always uses a single file named during configuration. For more information about SQL Server ce, see create database objects.
Configure SQL Server CE
- Right-clickCustom provider Mappings, PointingNewAnd then clickProvider Mapping.
- InAttributeClickTypenameAttribute. Click the ellipsis.
- InType Selector, Find and double-clickSqlcedatabase.
- InConnectionstringsClickNewAnd then clickConnection string.
- (Optional) enter a new name to setNameAttribute. This isConnectionstringThe name of the node. The default name isConnectionstring.
- InProvidernameAttribute section, modify the provider nameMicrosoft. sqlserverce. Client.
- InConnectionstringAttribute section, enter the ideal SQL Server ce connection string, for example:
Data Source = 'C: "MyApp" mydatabase. SDF'
The next process shows how to add an Oracle package. The volume El package service is a way to group stored procedures to common groups, usually based on their functions. When an application calls an oracle stored procedure in a package, the Code must use the package name as the prefix of the stored procedure. For exampleEmployee_pkgIn the package namedGetemployeenameWill callEmployee_pkg.getemployeename.
Set
Adding this code to the application will reduce portability, because the syntax is dedicated to Oracle
. Another replacement method is that the data access application block uses the package name as the prefix of the stored procedure. This means that the client code does not need to specify the package name when calling the stored procedure. To achieve this, use the Application Block
Information in the configuration file. Oraclepackage
The node saves a name/prefix pair. The name is the package name, And the prefix is a package-related string. All stored procedures starting with the specified prefix are assumed to be in the relevant package.
When an application calls a stored procedure, the Data Access Application Block checks whether it starts with a prefix in the configuration file. If yes, the Application Block adds the corresponding package name prefix to the stored procedure. (The Application Block uses the first match found ). If an asterisk (*) is specified as the prefix, the associated package is used for all stored procedures.
Configure the Oracle package
- Right-clickConnectionstring, PointingNewAnd then clickOraclepackages.
- ClickOraclepackage.
- Enter the name of the Oracle package to modifyNameAttribute. Default Value:Oraclepackage.
- InputPrefixAttribute Value.
The next process explains how to add custom provider mappings by associating the full names of providers and databases.
Configure custom providers
- Right-clickCustomprovidermappingsNode, pointingNewAnd then clickProvidermapping.
- (Optional) enter a new name to setNameAttribute. Enter the provider name or select from the drop-down list. The default provider isSystem. Data. sqlclient.ProvidernameThe property must beDbproviderfactoryThe provider name specified in the class.
- InTypenameAttribute section. Click the ellipsis (...) and use 'Type selector to select the full name of the Enterprise Library database type.
Usage tips
There are two points to remember about the configuration file.
- In
When you use the configuration console to open an existing application configuration file that contains data to access the Application Block, the configuration file is stored in machine. config.
File. Although the GUI interface of the configuration console allows you to edit connection strings, the configuration console cannot modify machine. config.
File, and the modifications do not work. The configuration console only saves modifications to the connection strings stored in the application configuration file.
- The configuration file is not encrypted. The configuration file may contain sensitive information about connection strings, user IDs, passwords, database servers, and categories. Encryption technology can be used to protect this information from unauthorized read/write operations. For more information about the encrypted configuration file, see configure application blocks.
2.1.1-source mode of data access application blocks
This topic lists the XML elements and attributes used to configure data access application blocks. You can manually edit XML data, but the Enterprise Library greatly simplifies this task. If you select to manually edit XML, you need to use the mode information contained in this topic.
The configuration file has the following section handler declaration:
<Configsections>
<Section name = "dataconfiguration"
Type = "Microsoft. Practices. enterpriselibrary. Data. configuration. databasesettings,
Microsoft. Practices. enterpriselibrary. Data, version = 3.1.0.0, culture = neutral, publickeytoken = NULL "/>
<Section name = "oracleconnectionsettings"
Type = "Microsoft. Practices. enterpriselibrary. Data. Oracle. configuration. oracleconnectionsettings,
Microsoft. Practices. enterpriselibrary. Data, version = 3.1.0.0, culture = neutral, publickeytoken = NULL "/>
</Configsections>
The Section handler Declaration includes the name of the Configuration Setting section and the class name of the section handler for configuring data in the Processing Section. The first configuration design section is named dataconfiguration, and the section handler class is namedDatabasesettings(InMicrosoft. Practices. enterpriselibrary. Data. ConfigurationIn the namespace ).
The Second Configuration Setting section is oracleconnectionsettings. Section handler Class Name:Oracleconnectionsettings(In
Microsoft. Practices. enterpriselibrary. Data. Oracle. ConfigurationIn the namespace ).
Connectionstrings Element
ConnectionstringsThe element lists the database connections that can be used by the application. This element is not required.
Attributes and child elements
The following section describesConnectionstringsThe attributes and child elements of the element.
ADD child element
AddElement isConnectionstringsThe child element of the element.AddElement to add a database connection. This element is not required and can have multipleAddElement.
Attribute
Table 1 listsAddThe attribute of the element.
Table 1: Add attributes
Attribute |
Description |
Name |
The logical name of the database instance accessed by the application. The name must be unique in the Section. This attribute is required. |
Providername |
The name of the provider. By default, the provider name is defined in the machine. config file.ProvidernameThe name must beDbproviderfactoryThe name of the provider specified in the class. This attribute is required. |
Connectionstring |
The connection string that can be used for the selected provider. This attribute is required. |
Dataconfiguration Element
The element is only useful when you need to specify the ing of a default database or custom provider.
Attribute
Table 2 listsDataconfigurationThe attribute of the element.
Table 2: dataconfiguration attributes
Attribute |
Description |
Defaultdatabase |
Name of the connection string instance. This instance is only used for application calls without the Instance name.Databasefactory. createdatabaseMethod. |
Providermappings child element
This isDataconfigurationThe child element of the element, only inDatabaseClass insteadGenericdatabaseYou must specify the ing of the provider only when providing the class. The SQL Server and Oracle databases are configured by default, so you do not need to specify them in this section. Specify a database example in this section as SQL Server ce.
ADD child element
AddYesProvidermappingsThe child element of the element.AddElement to add a database connection. This element is not required and can have multipleAddElement.
Attribute
Table 3 listsAddElement attributes
Table 3: Add attributes
Attribute |
Description |
Databasetype |
Derived fromDatabaseClass type name. This attribute is required. |
Name |
The name of the ADO. net provider type used. The name must be inDbproviderfactoryClass. This attribute is required. |
Oracleconnectionsettings
This element is required only when you need to specify the Oracle database package ing.
ADD child element
AddElement isOracleconnectionsettingsThe child element of the element.AddElement to add an oracle connection string instance. This element is not required. There can be multipleAddElement.
Attribute
Table 4 listsAddElement attributes
Table 4: Add attributes
Attribute |
Description |
Name |
The name of the Oracle connection string instance. This attribute is required. |
Packages child element
This isAddSpecifies an Oracle package. This element is required.
ADD child element
This isPackagesA child element of an element.AddElement to add an Oracle package. This element is not required. There can be multipleAddElement.
Attribute
Table 5 listsAddThe attribute of the child element.
Table 5: Add attributes
Attribute |
Description |
Name |
The name of the Oracle package. This attribute is required. |
Prefix |
The prefix of the Oracle package. This attribute is required. |
2.2-add application code
The Data Access Application Block is designed to support most database access scenarios. When adding your own application code, refer to the scenario in the key scenarios section and select the method that best matches your situation. Use the code in the scenario, or modify it to suit your needs.
First, you must prepare your own application to access the Application Block using data.
Prepare applications
- Add a reference to the data access application block assembly. In Visual Studio, right-click the project node in solution manager, and then clickAdd reference. ClickBrowseLabel, and then navigateMicrosoft. Practices. enterpriselibrary. Data. dll. Select the assembly, and then clickOKTo add references.
- Add to Enterprise Library kernel assembly in the same stepsMicrosoft. Practices. enterpriselibrary. Common. dllAndMicrosoft. Practices. objectbuilder. dll.
- (Optional) Add the following using Statement (C #) or imports Statement (Visual Basic) to the top of the source code file.
C #
Using Microsoft. Practices. enterpriselibrary. Data;
Using system. Data;
Visual Basic
Imports Microsoft. Practices. enterpriselibrary. Data
Imports system. Data
Note:For visual basic projects, you can use the reference pages of the project designer to manage references and import namespaces. To access the reference page, select a project node in the solution browser.ProjectClickAttribute. When the project designer appears, clickReferenceLabel.
Create a database object
All data access methods are relativeDatabase. AvailableDatabasefactoryTo createDatabaseObject. Generated by the factoryDatabaseThe specific type of the object is determined by the application configuration information.
You can use the configuration console to specify a default database instance. Do not pass the database instance name callCreatedatabaseMethod,DatabasefactoryCreate a database specified by the default instance. The following application code shows how to create a default instanceDatabaseObject.
C #
Database DB = databasefactory. createdatabase ();
Visual Basic
Dim dB as database = databasefactory. createdatabase ()
Another method is that the application code can specify a named database instance. For example, if an instance named "sales" is created on the configuration consoleDatabaseThe object code may be as follows.
C #
Database DB = databasefactory. createdatabase ("sales ");
Visual Basic
Dim dB as database = databasefactory. createdatabase ("sales ")
If the connection string of the database to be created is known, you must discard the configuration information of the application. Instead, you can directly create the database using the constructor.DatabaseObject. BecauseDatabaseA class is an abstract base class, so you must construct a derived type. DerivedDatabaseThe type determines the ADO. NET data provider. For example,SqldatabaseClass usageSqlclientfactoryProvider,SqlcedatabaseUseSqlceproviderfactoryAndOracledatabaseUseOracleclientfactoryProvider. Construct the correct type for the connection stringDatabaseClass is your responsibility.
The following code createsSqldatabaseObject.
C #
// Assume the method getconnectionstring exists in your application and
// Returns a valid connection string.
String myconnectionstring = getconnectionstring ();
Sqldatabase = new sqldatabase (myconnectionstring );
Visual Basic
'Assume the method getconnectionstring exists in your application and
'Returns a valid connection string.
Dim myconnectionstring as string = getconnectionstring ()
Dim dB as sqldatabase = new sqldatabase (myconnectionstring)
If a connection string is used by a data provider that is not an ADO. Net SQL data provider or an ORACLE data provider, you can createGenericdatabaseObject. In the createGenericdatabaseObject, must supportDbproviderfactoryObject.
Select an appropriate overload method
Each data access method has multiple reloads. The following descriptions and guidelines help you select the appropriate overload:
- Can accept ADO. NET 2.0DbcommandObject overload. These overloading provides maximum flexibility and control for each method.
- There is an overload that accepts the stored procedure name and the set of values used for storing the procedure parameter values. These reloads are convenient when an application calls a stored procedure with only input parameters.
- AcceptedSystem. Data. commandtypeAnd represents the reload of the command string. These convenient overloading are used when an application executes an inline SQL statement or stored procedure without parameters.
- At last, each overload contains an overload that accepts a transaction. This allows you to use the required overload type when executing methods in an existing transaction.
Each key scenario demonstrates one of the available reloads of a specific method, and many scenarios can be completed using other available reloads.