Introduction Microsoft introduced Enterprise Library in January 2005. Many companies have migrated their code from the independent Application Blocks to the Enterprise Library Blocks. In this article I will introduce the Data Access application block which is part of one of the blocks shipped with Enterprise Library.
Design of the Data Access Application Block
The Data Access Application Block was designed to achieve the following goals: 1.To encapsulate the logic used to perform the most common data access tasks 2.To relieve developers of the need to write duplicate code for common data access tasks 3.To minimize the need for custom code 4.To incorporate Microsoft best practices for data access
Usage of the Data Access Application Block Adding the reference: First thing you need to do is to add a reference to the dynamic link library. In order to use Data Access Application Block you should make a reference to
Microsoft.Practices.EnterpriseLibrary.Data.dll
Then import the namespaces
(if you are using vb.net)Imports Microsoft.Practices.EnterpriseLibrary.Data (if you are using c#) Using Microsoft.Practices.EnterpriseLibrary.Data Using Enterprise Library Data Access Application Block in vb.net : Let's see how we can return dataset to the calling block. We will see the code in small pieces so that you can easily understand it.
I have declared the function which returns the product’s list dataset.
Public Shared Function SelectProductsList(ByVal Productid As String) As DataSet
First we create a Database object which gets its configuration settings from the dataConfiguration.config file. The actual database type and connection string are stored in the configuration.
Dim myDatabase As Database = DatabaseFactory.CreateDatabase()
All Microsoft has done is create a wrapper that removes us from the details of creating the objects required to return a dataset Dim myCommand As DBCommandWrapper = myDatabase.GetStoredProcCommandWrapper("SelectProduct")
The code shown below specifies the parameter details.
myCommand.AddInParameter("@productid", DbType.Int32, Nothing)
To execute a stored procedure and return a dataset, we call the same static ExecuteDataSet method
Return myDatabase.ExecuteDataSet(myCommand)
If you want to To execute a stored procedure and return a datareader, we call the same static ExecuteReader method
return myDatabase.ExecuteReader(myCommand)
To execute a stored procedure and return a single value , we call the same static ExecuteReader method Return myDatabase.ExecuteScalar(myCommand))
Conclusion Data Access Application Block reduces the amount of code we must write, which reduces errors and increases the programmer’s productivity. It helps maintain consistent data access practices, both in an application and across the enterprise. It relieves developers from learning different programming models for different types of databases.
|
No responses found. Be the first to respond and make money from revenue sharing program.
|