CHAPTER 21 ADO.NET PART I: THE CONNECTED LAYER
"Provider=SQLOLEDB;Data Source=(local)\SQLEXPRESS;
Integrated Security=SSPI;Initial Catalog=AutoLot"/>
Doing this indicates that the System.Data.OleDb types are used behind the scenes, and gives the
following output:
***** Fun with Data Provider Factories *****
Your connection object is a: OleDbConnection
Your command object is a: OleDbCommand
Your data reader object is a: OleDbDataReader
***** Current Inventory *****
-> Car #32 is a VW.
-> Car #83 is a Ford.
-> Car #872 is a Saab.
-> Car #888 is a Yugo.
-> Car #1000 is a BMW.
-> Car #1011 is a BMW.
-> Car #2911 is a BMW.
Of course, based on your experience with ADO.NET, you might be a bit unsure exactly what the
connection, command, and data reader objects actually do. Don’t sweat the details for the time being
(quite a few pages remain in this chapter, after all!). At this point, it’s enough to know that you can use
the ADO.NET data provider factory model to build a single code base that can consume various data
providers in a declarative manner.
A Potential Drawback with the Data Provider Factory Model
Although this is a powerful model, you must make sure that the code base uses only types and methods
common to all providers through the members of the abstract base classes. Therefore, when authoring
your code base, you are limited to the members exposed by DbConnection, DbCommand, and the other types
of the System.Data.Common namespace.
Given this, you might find that this generalized approach prevents you from directly accessing some
of the bells and whistles of a particular DBMS. If you must be able to invoke specific members of the
underlying provider (e.g., SqlConnection), you can do so using an explicit cast, as in this example:
using (DbConnection cn = df.CreateConnection())
{
Console.WriteLine("Your connection object is a: {0}", cn.GetType().Name);
cn.ConnectionString = cnStr;
cn.Open();
if (cn is SqlConnection)
{
// Print out which version of SQL Server is used.
Console.WriteLine(((SqlConnection)cn).ServerVersion);
}
828