User_FSharp1123
User_FSharp1123

Reputation: 1161

Connection string: convert from config file to in code

I'm having some trouble getting my Entity Framework connection strings working from my main application and from my class library. Both my main application (an *.exe) and my class library (a COM *.dll that I want to use with Excel) will need to create a connection to either a SQL Server CE database or a SQL Server database.

At the moment, I define two 'base' connection strings in the config file, one for the SQL Server CE implementation and one for the SQL Server implementation. This works fine for my main application, as it reads the appropriate 'base' connection string from the config file (either SQL Server CE or SQL Server), I adjust the connection string value (e.g. file location via 'data source=' for SQL Server CE or database name for SQL Server), and I'm good to go. This however doesn't work well for my class library, as the config file depends on the application that is using the library. I'd like to therefore get rid of my config file dependency completely, by defining my connection strings in code as opposed to in the config file.

The current config file configuration looks as follows:

<add name="ConnectionCE" providerName="System.Data.SqlServerCe.4.0" connectionString="" />

<add name="ConnectionServer" providerName="System.Data.SqlClient" connectionString="" />

I then create the context as follows:

var context = new DbContext("name=ConnectionCE")
//Do things with the context above here, e.g. change the connection string value.

How can I convert the "ConnectionCE" and "ConnectionServer" connection strings so that I don't have to rely on the config file, and can create these directly in my C# code (with the correct provider)?

Thanks!

Upvotes: 0

Views: 1210

Answers (1)

rsage
rsage

Reputation: 56

DbContext(string) constructor accepts name or connection string.

You can simply build the connection string in code and pass it into the constructor.

You can use System.Data.SqlClient.SqlConnectionStringBuilder class to build connection string for SQL Server. I think, for SQL Server CE connection string, it is easy to use string.Format().

The code for SQL Server will look like:

var connStr = new SqlConnectionStringBuilder
{
    InitialCatalog = "YourDb",
    IntegratedSecurity = true,
    DataSource = @".\SQLServer",
};
var db = new DbContext(connStr.ConnectionString);

Provider should be specified for SQL Server CE, so the code will look like next:

var conn = DbProviderFactories.GetFactory("System.Data.SqlServerCe.4.0").CreateConnection();
conn.ConnectionString = "DataSource = \"C:\\ExistingDBFile.db\"";
var db = new DbContext(conn, true);

Upvotes: 2

Related Questions