使用一个DbContext在数据库之间切换



我正在开发一个具有相同模式的多个数据库的web应用程序。根据登录用户的不同,执行查询的数据库可能会有所不同。

我计划为每个DB创建连接字符串,当在存储库级别执行查询时,在创建DB上下文时更改连接字符串。

我的问题是,我试图在执行linq查询之前动态地将连接字符串名称传递给DB上下文,但失败了。

如果有人能帮我做这件事,并告诉我这种方法的优缺点,那就太好了。

您可以简单地在您的db上下文构造函数中添加一个接受连接字符串作为输入的重载:

public partial class SampleDbEntities
{
    public SampleDbEntities(string connectionString)
        : base(connectionString)
    {
    }
}

然后当你需要创建db上下文的实例时,使用这个重载并在连接字符串中注入合适的usernamepassword:

例如当你的连接字符串看起来像这样:

var connectionTemplate = @"provider=System.Data.SqlClient;" +
                       @"provider connection string=""data source={0};" +
                       @"initial catalog=SERVERNAME;persist security info=True;" +
                       @"user id={1};password={2};" +
                       @"MultipleActiveResultSets=True;App=EntityFramework""";

那么你可以使用string.Format(connectionTemplate, DatabaseName, UserName, Password)来创建连接字符串并传递给你的db上下文的构造函数;

//You will provide Databasename, UserName, Password based on your logic
//for example based on the user who logged in application.
var connectionString= string.Format(connectionTemplate, DatabaseName, UserName, Password);
var db = new SampleDbEntities(connectionString);

要更改DBContext的连接字符串,必须重写DBContext的构造函数。您必须添加一个带有连接参数的构造函数(您之前定义的连接…)

示例:public MYEntities(EntityConnection EntityConnection): base(entityConnection, true) {}

最新更新