Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF 5 Changing Connection String at Runtime

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;      } } 
like image 445
Mark Kram Avatar asked Oct 04 '12 23:10

Mark Kram


People also ask

How do I change the connection string in Entity Framework?

If you want to change the connection string go to the app. config and remove all the connection strings. Now go to the edmx, right click on the designer surface, select Update model from database, choose the connection string from the dropdown, Click next, Add or Refresh (select what you want) and finish.

How do I change the connection string after deployment?

If you save your connection string in the udl file, the user can change the connection via an interface by simply double clicking that file. You can set your connection string in the app to point to the udl file. You can also launch the udl interface programmatically if you want.

How do I update my connection string?

In the Properties window, expand the Connection node. To quickly modify the connection string, edit the ConnectionString property, or click the down arrow on the Connection property and choose New Connection.


1 Answers

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

like image 113
marianosz Avatar answered Sep 19 '22 20:09

marianosz