Entity Framework : Change connection string at runtime

会有一股神秘感。 提交于 2019-12-03 01:42:23

In my experience, I used the Database First mode in EF 6. The DbContext would be generated like below when I add Entity Data Model.

public TestEntities()
            : base("name=TestEntities")
        {
        }

The TestEntities represent the ConnectionString element in the App.Config

<connectionStrings>   
<add name="TestEntities" connectionString="..." providerName="System.Data.EntityClient" />
</connectionStrings>

But you can change the default code to below.

public partial class TestEntities : DbContext
    {
        public TestEntities()
            : base("name=TestEntities")
        {
        }

        public TestEntities(string sConnectionString)
            : base(sConnectionString)
        {
        }

...}

So you got two options to getting DB connection.

  1. using the default. The EF will find the connection string in the config file.

  2. passing the connection string to DbContext.

The code look like below.

EntityConnection entityConn =DBConnectionHelper.BuildConnection();
using (var db = new TestEntities(entityConn.ConnectionString))
{
....
}

As to the question How to build a EntityConnection?. Please see MSDN EntityConnection.

Hope it is helpful.

Thanks.

By default the name of the connection string to use in Entity Framework is inferred from the name of you DbContext class. However you can pass the connection string as a constructor parameter:

public class MyDbContext : DbContext, IUnitOfWork
{
    public MyDbContext(string connectionString)
        : base(connectionString)
    {
    }
}

Then you can configure StructureMap to pass in the current connection string e.g.

For<IUnitOfWork>().Use(ctx => new MyDbContext(TheConnectionStringToUse));

This could come from a static value that you set in your code, the current session etc.

I am going to suggest a completely different path. Assuming you have your connection strings set up in your web.config, which you say you do, why wouldn't you use web.debug.config and web.release.config transforrms to set your connection strings appropriately?

i.e. in web.debug.config

<connectionStrings>
    <add name="FooEntities" connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider connection string="Data Source=IP,PORT\Instancename;
    Initial Catalog=Foo;Persist Security Info=True;User ID=admin;Password=password;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient"/>
</connectionStrings>

and a web.release.config as such

<connectionStrings xdt:Transform="Replace">
    <add name="FooEntities" connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider connection string="Data Source=LIVEIP,PORT\Instancename;
    Initial Catalog=Foo;Persist Security Info=True;User ID=admin;Password=password;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient"/>
</connectionStrings>

A very thorough explanation is available here

Tom
 public partial class YourDBContextClass
 {
    // Add a constructor to allow the connection string name to be changed
 public YourDBContextClass(string connectionStringNameInConfig)
        : base("name=" + connectionStringNameInConfig)
    {
    }
}

Add multiple connection strings to your web or app.config file.

in your program code:

YourDBContextClass dbcontext = new YourDBContextClass("alternateconnectionstringname");

The two approaches are good for two different situations:

  • The transform is good for deploying a connection string that only changes for the different evironments (test, production).

  • The approach of adding a constructor (which takes the connection string name) in a separate file to extend the partial dbcontext class allows the connection to be switched at runtime.

Add two different Connection String in App.Config File using different Name.

Set Current connection String Name in Entity Constructor using Overloading.

In Code File

public ASM_DBEntities()
        : base("name=ASM_DBEntities")
    {
    }

    public ASM_DBEntities(string conn)
        : base("name=ASM_DBEntities1")
    {

    }

When we pass string with object then is use different connection string.

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