开发者

Switch connection strings based on environment with EF 4.1/DbContext

I have seen several posts about this but have not been able to create a usable solution from the responses. Perhaps due to a lack of understanding.

The hosting provided requires that an identical code base be used on staging and production, including connection string.

How do I switch the connection string for DbContext?

I understand I can do something like this:

public FooEntities() : base("Applica开发者_StackOverflow中文版tionServices") { }

But this is not dynamic - it merely sets it at runtime.

So how would I actually CHOOSE the connection string at runtime?


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜