Working with the Common Provider Model

In ADO.NET 1.x, you could code to either the provider-specific classes, such as SqlConnection, or the generic interfaces, such as IDbConnection. If there was a possibility that the database you were programming against would change during your project, or if you were creating a commercial package intended to support customers with different databases, then you had to use the generic interfaces. You cannot call a constructor on an interface, so most generic programs included code that accomplished the task of obtaining the original IDbConnection by means of their own factory method, such as a GetConnection method that would return a provider-specific instance of the IDbConnection interface.

ADO.NET today has a more elegant solution for getting the provider-specific connection. Each data provider registers a ProviderFactory class and a provider string in the .NET machine.config file. A base ProviderFactory class (DbProviderFactory) and a System.Data.Common.ProviderFactories class can return a DataTable of information (via the GetFactoryClasses method) about different data providers registered in machine.config, and can return the correct ProviderFactory given the provider string (called ProviderInvariantName) or by using a DataRow from this DataTable. Instead of writing your own framework to build connections based on the name of the provider, ADO.NET now makes it much more straightforward, flexible, and easy to solve this problem.

Now take ...

Get Professional Visual Basic 2012 and .NET 4.5 Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.