Without an App, create a DbProviderFactory. Config

ado.net dbproviderfactories entity-framework sqlite

Question

Although my data layer (based on Entity Framework) uses DbProviderFactories and my database is SQLite, I don't need an App.Config to have the following code:

<configuration>
  <system.data>
    <DbProviderFactories>
      <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" />
    </DbProviderFactories>
  </system.data>
</configuration>

Instead, I would want to programmatically insert it into my data layer. Anyone have a solution for this?

EDIT:

This is because some of my data layers don't need the App.Config settings or have them hard-tied to the data layer, and I use an IoC container to choose the data layer.

1
37
3/22/2014 1:16:32 AM

Accepted Answer

The next will likely produce sunspots and end western civilisation. Even though it could start a dispute about "Duct Tape Programming" (put an end to it! ), it is effective (for now)

try
{
    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) { }
54
3/15/2014 7:05:14 PM

Popular Answer

A SQLite solution was offered by JoshRivers above. The fact that I was able to utilize his example to get it working for MySQL proves that this can be applied to other adapters as well. This is what I've turned into, something a little more general. This is for the.NET connection version 6.6.5.0 and ought to be executed when the application starts (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=6.6.5.0, 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;
        break;
    }
}

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


Related Questions





Related

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