CHAPTER 21 ADO.NET PART I: THE CONNECTED LAYER
Each of the Microsoft-supplied data providers contains a class type that derives from
System.Data.Common.DbProviderFactory. This base class defines several methods that retrieve providerspecific data objects. Here is a snapshot of the relevant members of DbProviderFactory:
public abstract class DbProviderFactory
{
...
public virtual DbCommand CreateCommand();
public virtual DbCommandBuilder CreateCommandBuilder();
public virtual DbConnection CreateConnection();
public virtual DbConnectionStringBuilder CreateConnectionStringBuilder();
public virtual DbDataAdapter CreateDataAdapter();
public virtual DbDataSourceEnumerator CreateDataSourceEnumerator();
public virtual DbParameter CreateParameter();
}
To obtain the DbProviderFactory-derived type for your data provider, the System.Data.Common
namespace provides a class type named DbProviderFactories (note the plural in this type’s name). You
can use the static GetFactory() method to obtain the specific DbProviderFactory object of the specified
data provider; do this by specifying a string name that represents the .NET namespace containing the
provider’s functionality, like so:
static void Main(string[] args)
{
// Get the factory for the SQL data provider.
DbProviderFactory sqlFactory =
DbProviderFactories.GetFactory("System.Data.SqlClient");
...
}
Of course, rather than obtaining a factory using a hard-coded string literal, you could instead read in
this information from a client-side *.config file (much like the earlier MyConnectionFactory example).
You will learn how to do this shortly; for the moment, you can obtain the associated provider-specific
data objects (e.g., connections, commands, and data readers) once you have obtained the factory for
your data provider.
Note For all practical purposes, you can regard the argument sent to DbProviderFactories.GetFactory()
as the name of the data provider’s .NET namespace. In reality, the machine.config value uses this string value to
load the correct library dynamically from the Global Assembly Cache.
A Complete Data Provider Factory Example
For a complete example, you can create a new C# Console Application (named DataProviderFactory)
that prints out the automobile inventory of the AutoLot database. For this initial example, you will hardcode the data access logic directly within the DataProviderFactory.exe assembly (to keep things simple
for the time being). However, when you begin to dig into the details of the ADO.NET programming
model, you will isolate your data logic to a specific .NET code library that you will use for the remainder
of this book.
825