I want to create a data access layer that works with any data provider.
I know it's possible to create a DbCommand
using the factory method available on the connection.
objDbCon.CreateCommand();
However, I could not find anything to create a DbDataAdapter
. Is this is a bug in ADO.NET or what?
This example takes a DbConnection object as an argument. A DbCommand is created to select data from the Categories table by setting the CommandText to a SQL SELECT statement. The code assumes that the Categories table exists at the data source. The connection is opened and the data is retrieved using a DbDataReader.
A DataAdapter is used to retrieve data from a data source and populate tables within a DataSet. The DataAdapter also resolves changes made to the DataSet back to the data source.
As of .NET 4.5, when writing provider independent code, you can now use the DbProviderFactories.GetFactory
overload that accepts a DbConnection
to obtain the correct provider factory from which you can then create a data adapter.
Example:
DbDataAdapter CreateDataAdapter(DbConnection connection) { return DbProviderFactories.GetFactory(connection).CreateDataAdapter(); }
It seems someone on the ADO.NET team read Ian Boyd comment on his answer... :)
DbProviderFactory.CreateDataAdapter *
Also you can get all registered DbProviders via DbProviderFactories class.
*I think this is a wrong place for this method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With