实体框架在运行时多个数据库(相同的模式)?

Kev*_*vin 23 asp.net asp.net-mvc entity-framework

首先,让我说我对EF很新.话虽如此,这是我的困境:

将有一个ASP.NET应用程序迁移到ASP.NET MVC.我想为此使用EF.有一个主数据库存储"客户信息".除此之外,每个"客户"都有自己的数据库.这些是我们的约束.

目前,主数据库中的客户端信息使我能够为每个客户端构建连接字符串并进行单独的SQL调用.

我如何在Entity Framework中完成同样的事情?每个数据库都具有相同的架构.有没有办法以编程方式切换连接字符串?这些数据库当前位于同一台服务器上,但这不是必需的,它可能是完全不同的服务器.

有任何想法吗?

Web.config中的多个连接字符串将是最后的手段.即便如此,我也不确定如何准确地将其连接起来.

先感谢您.

Jac*_*itt 8

如果在实体对象的构造函数中使用EntityConnection,则可以非常轻松地更改数据库.

EntityConnection con = new EntityConnection(connString);
con.ChangeDatabase(dbName);
using (Entities context = new Entities(con))
{
    // Some code here
}
Run Code Online (Sandbox Code Playgroud)


Bra*_*don 5

构建数据上下文时,以下是如何通过修改Context.Connection属性以编程方式在运行时更改连接字符串:

//Get the connection string from app.config and assign it to sqlconnection string builder
SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder(((EntityConnection)context.Connection).StoreConnection.ConnectionString);
sb.IntegratedSecurity = false;
sb.UserID ="User1";
sb.Password = "Password1";

//set the object context connection string back from string builder. This will assign modified connection string.
((EntityConnection)context.Connection).StoreConnection.ConnectionString = sb.ConnectionString; 
Run Code Online (Sandbox Code Playgroud)

摘自:http://sivapinnaka.spaces.live.com/blog/cns!B027EF7E7070AD69!211.entry