.net 在多个数据库上使用实体框架

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17941225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 12:22:59  来源:igfitidea点击:

Using entity framework on multiple databases

.netentity-framework

提问by clifford.duke

I am writing a payroll system that will integrate with a pre-existing system. The original system had a master database that handled user management and some global configuration, below that there are multiple databases each identical in structure, basically each database is one companies payroll database, all these are tied to the main database because it belongs to a parent company who has many subsidiaries each with their own HR department.

我正在编写一个将与现有系统集成的工资系统。原来的系统有一个主数据库,负责用户管理和一些全局配置,下面有多个结构相同的数据库,基本上每个数据库都是一个公司的工资数据库,所有这些都绑定到主数据库,因为它属于一个父数据库公司拥有许多子公司,每个子公司都有自己的人力资源部门。

What I was wondering is if there is any way that I can, based on either a cookie or another method that stores what company they wish to connect to, dynamically change the entity frameworks target database based on their input using a filter?

我想知道的是,是否有任何方法可以基于 cookie 或其他存储他们希望连接的公司的方法,使用过滤器根据他们的输入动态更改实体框架目标数据库?

Here's an example:

下面是一个例子:

User A logs in to the site, page loads with available companies that the user has permission to access, user will then select a company, they have admin privileges in that company, they add an employee, before that action is run, asp.net will switch the connection string to the appropriate database then add the record.

用户 A 登录到该站点,页面加载了用户有权访问的可用公司,然后用户将选择一家公司,他们在该公司拥有管理员权限,他们添加了一名员工,在该操作运行之前,asp.net将连接字符串切换到适当的数据库,然后添加记录。

采纳答案by phil soady

EF6 has better support for multiple DB access from Same context. Here is a snippet from EF5. Managing the database initializer setting prior is important. You may not want to trigger ANY migrations. i.e, use this before

EF6 更好地支持来自相同上下文的多个数据库访问。这是 EF5 的一个片段。事先管理数据库初始值设定项设置很重要。您可能不想触发任何迁移。即,使用此之前

Database.SetInitializer(new ContextInitializerNone<MyDbContext>());

Database.SetInitializer(new ContextInitializerNone<MyDbContext>());

but to answer the question: Yes you can

但要回答这个问题:是的,你可以

var conn = GetSqlConn4DbName(dataSource,dbName );
var ctx = new MyDbContext(conn,true);



public DbConnection GetSqlConn4DbName(string dataSource, string dbName) {
        var sqlConnStringBuilder = new SqlConnectionStringBuilder();
        sqlConnStringBuilder.DataSource = String.IsNullOrEmpty(dataSource) ? DefaultDataSource : dataSource;
        sqlConnStringBuilder.IntegratedSecurity = true;
        sqlConnStringBuilder.MultipleActiveResultSets = true;

        var sqlConnFact = new SqlConnectionFactory(sqlConnStringBuilder.ConnectionString);
        var sqlConn = sqlConnFact.CreateConnection(dbName);
        return sqlConn;
    }


 public class ContextInitializerNone<TContext> : IDatabaseInitializer<TContext> where TContext : DbContext
{
    public void InitializeDatabase(TContext context) {  }
}

Also see StackOverflow answer using migration, sample code, and dynamic db connection

另请参阅使用迁移、示例代码和动态数据库连接的 StackOverflow 答案

回答by Sakhu

It is very simple. I have:

这很简单。我有:

public WMSEntities() : base("name=WMSEntities") //WMSEntities is conection string name in     web.config also the name of Entitiframework
{
}

already in autogenerated Model.Context.cs of edmx folder

已经在 edmx 文件夹的自动生成的 Model.Context.cs 中

To connect to multiple database in runtime, I created another constructor that takes connection string as parameter like below in same file Model.Context.cs

为了在运行时连接到多个数据库,我在同一个文件 Model.Context.cs 中创建了另一个将连接字符串作为参数的构造函数,如下所示

public WMSEntities(string connStringName)
    : base("name=" + connStringName)
{
}

Now I added other connection string in Web.Config for example

例如,现在我在 Web.Config 中添加了其他连接字符串

<add name="WMSEntities31" connectionString="data source=TESTDBSERVER_NAME;initial catalog=TESTDB;userid=TestUser;password=TestUserPW/>

<add name="WMSEntities" connectionString="data source=TESTDBSERVER_NAME12;initial catalog=TESTDB12;userid=TestUser12;password=TestUserPW12/>

Then, when connecting to database I call below method passing connetionString name as parameter

然后,当连接到数据库时,我调用下面的方法传递 connetionString 名称作为参数

public static List<v_POVendor> GetPOVendorList(string connectionStringName)
{
    using (WMSEntities db = new WMSEntities(connectionStringName))
    {               
        vendorList = db.v_POVendor.ToList();                 
    }
}