Data Access Application Block - Reduce ADO.NET Code in Your Applications
by David Hayden ( ASP.NET Developer )
This is a sample taken from my presentation on Enterprise Library 2.0 that clearly shows how much code is reduced by using the Data Access Application Block in Enterprise Library 2.0. Most people were rather amazed by the difference, so I thought it was worth a post so that you can see the value of this application block.
I have 3 examples that call a stored procedure and return a DataReader. One uses DAAB. One uses SqlClient. And the last one uses the generic database providers ( which Enterprise Library 2.0 DAAB is using under the covers ). Note that you not only get a reduction of code with DAAB, but you are also doing generic database programming.
Enterprise Library 2.0 Data Access Application Block
Database db = DatabaseFactory.CreateDatabase();
using (IDataReader dr = db.ExecuteReader("GetContacts"))
{
// Do Something Useful
}
System.Data.SqlClient
string connectionString =
WebConfigurationManager.
ConnectionStrings["LocalSqlServer"].
ConnectionString;
using (SqlConnection connection =
new SqlConnection(connectionString))
using (SqlCommand command =
new SqlCommand("GetContacts", connection))
{
connection.Open();
command.CommandType = CommandType.StoredProcedure;
using (IDataReader dr = command.ExecuteReader())
{
// Do Something Useful
}
}
DbProviderFactory
// Get Provider Factory
string providerName =
WebConfigurationManager.
ConnectionStrings["LocalSqlServer"].
ProviderName;
DbProviderFactory factory =
DbProviderFactories.GetFactory(providerName);
// Create Connection
using (DbConnection connection = factory.CreateConnection())
{
String connectionString =
WebConfigurationManager.
ConnectionStrings["LocalSqlServer"].ConnectionString;
connection.ConnectionString = connectionString;
// Create Select Command
using (DbCommand selectCommand = factory.CreateCommand())
{
selectCommand.CommandType = CommandType.StoredProcedure;
selectCommand.CommandText = "GetContacts";
selectCommand.Connection = connection;
connection.Open();
using (IDataReader dr = selectCommand.ExecuteReader())
{
// Do Something Useful
}
}
}
When you start using parameters you even get more of a reduction in code, but I think the examples above prove the point. You not only reduce the amount of code you write when using DAAB, but you also avoid dealing with certain issues like connection management and creating command objects. The code is also a heck of a lot easier to read.
Source: David Hayden ( ASP.NET Developer )
Enterprise Library Tutorials and Examples