Entity Framework change connection at runtime

asp.net-web-api c# connection-string entity-framework

Accepted Answer

I realize I'm a little late with this response, but I believe there may be a clever extension method that could help. With a few little framework calls and the EF convention over configuration, we can benefit.

The commented code and example usage are as follows:

class of extension methods:

public static class ConnectionTools
    // all params are optional
    public static void ChangeDatabase(
        this DbContext source,
        string initialCatalog = "",
        string dataSource = "",
        string userId = "",
        string password = "",
        bool integratedSecuity = true,
        string configConnectionStringName = "") 
        /* this would be used if the
        *  connectionString name varied from 
        *  the base EF class name */
            // use the const name if it's not null, otherwise
            // using the convention of connection string = EF contextname
            // grab the type name and we're done
            var configNameEf = string.IsNullOrEmpty(configConnectionStringName)
                ? source.GetType().Name 
                : configConnectionStringName;

            // add a reference to System.Configuration
            var entityCnxStringBuilder = new EntityConnectionStringBuilder

            // init the sqlbuilder with the full EF connectionstring cargo
            var sqlCnxStringBuilder = new SqlConnectionStringBuilder

            // only populate parameters with values if added
            if (!string.IsNullOrEmpty(initialCatalog))
                sqlCnxStringBuilder.InitialCatalog = initialCatalog;
            if (!string.IsNullOrEmpty(dataSource))
                sqlCnxStringBuilder.DataSource = dataSource;
            if (!string.IsNullOrEmpty(userId))
                sqlCnxStringBuilder.UserID = userId;
            if (!string.IsNullOrEmpty(password))
                sqlCnxStringBuilder.Password = password;

            // set the integrated security status
            sqlCnxStringBuilder.IntegratedSecurity = integratedSecuity;

            // now flip the properties that were changed
                = sqlCnxStringBuilder.ConnectionString;
        catch (Exception ex)
            // set log item if required

standard usage

// assumes a connectionString name in .config of MyDbEntities
var selectedDb = new MyDbEntities();
// so only reference the changed properties
// using the object parameters by name
        initialCatalog: "name-of-another-initialcatalog",
        userId: "jackthelady",
        password: "nomoresecrets",
        dataSource: @".\sqlexpress" // could be ip address 120.273.435.167 etc

Although I'm aware that you already have the very minimum of functionality, I thought this could provide some variety.

11/27/2013 10:42:50 PM

Popular Answer

DbContext has an overload constructor that takes either the connection string's name or the string itself. Create your own version, then implement it and provide it to the base constructor.

public class MyDbContext : DbContext
    public MyDbContext( string nameOrConnectionString ) 
        : base( nameOrConnectionString )

When you instantiate your connection string, just supply the connection string's name or the connection string itself.DbContext

var context = new MyDbContext( "..." );

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