使用在多个数据库实体框架多个、实体、框架、数据库

2023-09-02 10:49:36 作者:忽略不计的爱

我写一个工资管理系统,将有pre-现有的系统集成。原系统有这样的处理的用户管理和一些全局配置一个主数据库,下面有多个数据库中的结构的每个相同,基本上每个数据库是企业工资单数据库,所有这些都连接到主数据库,因为它属于父公司谁拥有众多的子公司每个都有自己的HR部门。

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.

我想知道的是,如果有框架的基础上使用过滤器的输入目标数据库,我可以,主要是基于一个cookie,或者他们希望连接到什么公司专卖店,动态改变实体另一种方法什么办法?

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?

下面是一个例子:

在该网站用​​户A登录,页面加载与现有企业用户具有访问权限的用户将选择一个公司,他们在该公司管理权限,他们增加雇员,该操作运行之前, asp.net将连接字符串切换到相应的数据库,然后添加记录。

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.

推荐答案

EF6具有从同样的情况下多个数据库的访问更好的支持。下面是EF5片段。 事先管理数据库初始化设置非常重要。 你可能不希望触发任何迁移。 即,在

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

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

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

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) {  }
}

也看到的StackOverflow的答案用迁移,样品code和动态数据库连接