Switch connection strings based on environment with EF 4.1/DbContext

眉间皱痕 提交于 2019-12-01 07:31:33

Yes public FooEntities() : base("ApplicationServices") { }

FooEntities inheriting from ObjectContext

You could also write

public FooEntities() : base(YourStaticMethodToGetConnectionString()) { }

Then you could pull the connection string from the web.config based on some environment setting

I'm reviewing this right now because I will dev local and then deploy to cloud. Therefore, want to dynamically switch connection strings being used by data context. My plan is to configure the needed connection strings in standard "connectionStrings" section of Web.config, and then place logic in the DbContext constructor, like:

public partial class MyApplicationDbContext : DbContext
{
    public MyApplicationDbContext()
        : base("name=cloud")
    {
        Database.Connection.ConnectionString = 
            ConnectionStringHelpers.GetHostBasedConnectionString();
    }

    // abbreviated..
}

Alternate:

public partial class MyApplicationDbContext : DbContext
{
    public MyApplicationDbContext()
        : base(ConnectionStringHelpers.GetHostBasedConnectionString())
    {
    }

    // abbreviated..
}

Helper:

public class ConnectionStringHelpers
{
    public static string GetHostBasedConnectionString()
    {
        return GetConnectionStringByName(GetHostBasedConnectiongStringName());
    }

    public static string GetHostBasedConnectiongStringName()
    {
        switch (System.Net.Dns.GetHostName())
        {
            case "myHostname": return "local";   // My local connection
            case "ip-ABCD123": return "cloud";   // Cloud PaaS connection
            default: return "cloud";
        }           
    }

    public static string GetConnectionStringByName(string name)
    {
        return ConfigurationManager.ConnectionStrings[name].ConnectionString;
    }
}

And in my Web.config file:

<connectionStrings>
    <add name="local" connectionString="..." providerName="System.Data.SqlClient" />
    <add name="cloud" connectionString="..." providerName="System.Data.SqlClient" />
</connectionStrings>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!