Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a DbDataAdapter given a DbCommand or DbConnection?

Tags:

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?

like image 975
Karim Avatar asked Aug 15 '10 19:08

Karim


People also ask

What is DbCommand and DbConnection objects?

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.

What is data adapter in C#?

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.


2 Answers

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... :)

like image 163
João Angelo Avatar answered Sep 28 '22 00:09

João Angelo


DbProviderFactory.CreateDataAdapter *

Also you can get all registered DbProviders via DbProviderFactories class.

*I think this is a wrong place for this method.

like image 40
Sergey Mirvoda Avatar answered Sep 28 '22 01:09

Sergey Mirvoda