Database Independent Development using ASP.NET 2.0 - Developing a common class which works with Factories: explanation
(Page 3 of 6 )
This section explains the source code provided in the previous section in a step-by-step manner. Let us start with the private members:
Private _DBProviderName As String
Private _ConnectionString As String
Those two are the variables which hold the .NET data provider to use and the connection string to connect. For example, _DBProviderName can be assigned with "System.Data.SqlClient" (as a string itself) to work with Microsoft SQL Server specific .NET data provider. Similarly, you can even assign "Oracle.DataAccess.Client" to work with ODP.NET (or Oracle's .NET data provider to access Oracle).
Going a bit further down, we have the following constructor:
Public Sub New(ByVal ProviderName As String, ByVal ConnectionString As String)
_DBProviderName = ProviderName
_ConnectionString = ConnectionString
If DbProviderFactories.GetFactoryClasses.Select _
("InvariantName='" & _DBProviderName & "'").Length = 0 Then
Throw New Exception("Invalid .NET Data Provider specification: " & _DBProviderName)
Exit Sub
End If
_dpf = DbProviderFactories.GetFactory(_DBProviderName)
End Sub
The above constructor receives ProviderName (ex: System.Data.SqlClient as a string) and ConnectionString as parameters, and checks whether or not the provider is installed on the machine. If the provider is not installed (say ODP.NET is not installed but you are trying to use Oracle.DataAccess.Client), then it raises an exception.
If the .NET data provider is already installed, then it creates a factory object (based on the provider specification), which can be used later to create other objects like connections, commands etc. specific to that provider. Proceeding further down, we have the following:
Public Function GetDBConnection() As DbConnection
Dim dbConn As DbConnection = GetDBProviderFactory.CreateConnection
dbConn.ConnectionString = _ConnectionString
Return dbConn
End Function
The above function simply creates a Connection object (based on the .NET data provider selected by the factory), assigns the connection string and returns the same Connection object to the calling method. We can use this Connection object later to create other objects like Command, DataAdapter and so forth.
Going further down, we have two more function which create and return Command/DataAdapter objects to the calling methods:
Public Function GetDBCommand() As DbCommand
Dim dbCmd As DbCommand = GetDBProviderFactory.CreateCommand
dbCmd.Connection = GetDBConnection()
Return dbCmd
End Function
Public Function GetDBDataAdapter() As DbDataAdapter
Dim dbAdap As DbDataAdapter = GetDBProviderFactory.CreateDataAdapter
Return dbAdap
End Function
Next: Developing a simple data access class to work with the factory: skeleton >>
More ASP.NET Articles
More By Jagadish Chaterjee