Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

entity framework - 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; 
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...