Don't understand why DbProviderFactories.GetFactory is returning NULL

3.7k Views Asked by At

In my C# application, I have roughly the following code:

In App.Config:

<connectionStrings>
  <add name="Con1" connectionString="..." providerName="System.Data.Odbc"/>
</connectionStrings>

In My Code:

static DbConnection createConnection(ConnectionStringSettings conn_str)
{
    DbProviderFactory factory = DbProviderFactories.GetFactory(conn_str.ProviderName);
    var retval = factory.CreateConnection();
    retval.ConnectionString = conn_str.ConnectionString;
    return retval;
}

This creates for me a connection variable, conn and works great (I can open the connection, query it, etc), so I know I'm referencing the correct libraries.

However, later on, I need to get the factory again and use:

DbProviderFactory factory = DbProviderFactories.GetFactory(conn);

But, for whatever reason, I get back that factory = null.

Am I doing something plainly wrong?

2

There are 2 best solutions below

2
On

I just tried the following code:

DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.Odbc");
var retval = factory.CreateConnection();

factory came back as not null. There is something else going on since this code should work fine.

1
On

I don't know if it helps but I've been facing the same problem. I tried to use a OleDbConnection to get the factory with no luck. I used the same database but through a SqlConnection and it worked fine. Maybe it has to do with the type of connection, but the documentation doesn't give insight about that. If DbProviderFactories.GetFactory doesn't work with some kinds of DbConnection, it should at least throw an exception. Try changing to another connection type. Greetings and good luck.