33

Ok, I want to recreate a project that I created using EF 4.1 to EF 5.0, simple enough or at least I thought. One of the things in my old project is that I was able to change the database connection string at runtime in EF 4.1:

using (var myContext = new MyEntities(ConnectionString))
{

}

Easy-peasy but in EF 5.0 you have to do this differently:

string connectionString = "data source=LocalHost;initial catalog=MyDatabase;user id=MyUserName;password=MyPassword;multipleactiveresultsets=True;App=EntityFramework";

using (var myContext = new MyEntities())
{
         myContext.Database.Connection.ConnectionString = connectionString;
}

Now, this took me a better part of two hours to figure out, so I guess my question is this the proper way of changing the connection string at runtime or not? If it is why did they make this change?

I did find this Link but it didn't work. I received the error as detailed in the first comment of the first answer by Ladislav Mrnka. I later found this Link which seems to work fine.

UPDATE

I re-read the first link I posted and I found another solution, I simply created a partial class:

public partial class MyEntities : DbContext
{
    public MyEntities(string connectionString) : base(connectionString) 
    {
          Database.Connection.ConnectionString = connectionString; 
    }
}
Community
  • 1
  • 1
Mark Kram
  • 5,672
  • 7
  • 51
  • 70
  • 16
    You should write your edit as an answer and accept it... – SRKX Feb 20 '13 at 13:35
  • In your answer, the line `Database.Connection.ConnectionString = connectionString;` is redundant, because that operation is already done by the base constructor. – Nick Udell May 20 '16 at 14:24

3 Answers3

6

Use the context constructor overload that takes the connection string as a parameter.

marianosz
  • 1,234
  • 10
  • 8
1

Create a class with the same name as the Target ContextClass class next to the main class

like this :

public CustomerContext( string connectionString) 
    : base(connectionString)
{
}

For using :

using (var context = new CustomerContext("connectionString"))
{

}

Or

var customerContext=new CustomerContext("yorConnectionString");

var customer=CustomerContext.customer.FirstOrDefault(x=>x.id==1).FirstName;
Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190
0

Have a look at other link Setup Entity Framework For Dynamic Connection String. It says - " you can do it by creating another partial class as the Entities class is declared partial"

Community
  • 1
  • 1
Faiyaz
  • 1,391
  • 11
  • 9