Switch connection strings based on environment with EF 4.1/DbContext

久未见 提交于 2019-12-19 08:54:51

问题


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("ApplicationServices") { }

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

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


回答1:


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




回答2:


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>


来源:https://stackoverflow.com/questions/7434753/switch-connection-strings-based-on-environment-with-ef-4-1-dbcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!