Without an App, create a DbProviderFactory. Config

ado.net dbproviderfactories entity-framework sqlite


I am using DbProviderFactories in my data layer (based on Entity Framework) and am using SQLite for my database, but I don't have to have a App.Config to have the following code:

      <remove invariant="System.Data.SQLite"/>
      <add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".Net Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />

Instead I would like to have my data layer put that in programmatically. Anyone know a way to do this?


The reason for this is that I am using a IoC container to pick the data layer and some of my data layers don't need the App.Config values, or have them be hard tied to the data layer.

3/22/2014 1:16:32 AM

Accepted Answer

The following will probably cause sunspots and overthrow western civilization. It may even cause a debate about Duct Tape Programming (make it stop!), but it works (for now)

    var dataSet = ConfigurationManager.GetSection("system.data") as System.Data.DataSet;
    dataSet.Tables[0].Rows.Add("SQLite Data Provider"
    , ".Net Framework Data Provider for SQLite"
    , "System.Data.SQLite"
    , "System.Data.SQLite.SQLiteFactory, System.Data.SQLite");
catch (System.Data.ConstraintException) { }
3/15/2014 7:05:14 PM

Popular Answer

JoshRivers above posted a solution for SQLite. This can in fact be used for other adapters as well- I was able to get it working for MySQL using his example. I have wrapped this into something a bit more generic. This should be run once the application starts and is for the .NET connector version (but I imagine it is good for other versions as well.)

string dataProvider = @"MySql.Data.MySqlClient";
string dataProviderDescription = @".Net Framework Data Provider for MySQL";
string dataProviderName = @"MySQL Data Provider";
string dataProviderType = @"MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=, Culture=neutral, PublicKeyToken=c5687fc88969c44d";

bool addProvider = true;
var dataSet = ConfigurationManager.GetSection("system.data") as DataSet;
foreach (DataRow row in dataSet.Tables[0].Rows)
    if ((row["InvariantName"] as string) == dataProvider)
        // it is already in the config, no need to add.
        addProvider = false;

if (addProvider)
    dataSet.Tables[0].Rows.Add(dataProviderName, dataProviderDescription, dataProvider, dataProviderType);

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow