Entity Framework : Change connection string at runtime

asp.net-mvc c# dependency-injection entity-framework structuremap

Popular Answer

In my encounter, I applied theDatabase First setting in EF 6.DbContext would be produced as shown below if I addedEntity Data Model .

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

The TestEntities symbolize theConnectionString portion of the App.Config

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

However, you can modify the default code to the following.

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

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

...}

There are so two ways to establish a database connection.

  1. using the standard. The connection string is located in the configuration file by the EF.

  2. DbContext is given the connection string.

The code appears as follows.

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

Regarding the queryHow to build a EntityConnection? . Observe EntityConnection on MSDN, please.

I hope it's useful.

Thanks.

18
10/21/2014 7:28:06 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow