EF 5在运行时更改连接字符串 [英] EF 5 Changing Connection String at Runtime

查看:151
本文介绍了EF 5在运行时更改连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我想重新创建一个使用EF 4.1到EF 5.0创建的项目,足够简单或至少我想。我的旧项目中的一件事是,我可以在运行时在EF 4.1中更改数据库连接字符串:

 使用(var myContext = new MyEntities(ConnectionString))
{

}



  string connectionString =data source = LocalHost;初始目录= MyDatabase;用户id = MyUserName; password = MyPassword; multipleactiveresultsets = True; App = EntityFramework; 

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

现在,我花了两个多小时的时间,我想我的问题是这是在运行时更改连接字符串的正确方法吗?如果是这样做的原因呢?



我找到了这个 Link ,但它没有起作用。我收到了Ladislav Mrnka的第一个答案的第一个评论中详细的错误。后来我发现这个链接,似乎工作正常。



更新



我重新阅读了第一个链接我发布了,我发现另一个解决方案,我只是创建了一个部分类:

  public partial class MyEntities:DbContext 
{
public MyEntities(string connectionString):base(connectionString)
{
数据库.Connection.ConnectionString = connectionString;
}
}


解决方案

使用将连接字符串作为参数的上下文构造函数重载。


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; 
    }
}

解决方案

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

这篇关于EF 5在运行时更改连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆