如何通过连接字符串创建多个数据库环境Intances? [英] How create multiple db context intances by conntecting strings?

查看:246
本文介绍了如何通过连接字符串创建多个数据库环境Intances?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,MVC代码第一个应用程序我有

In C#, MVC code first application I have

public class CarContext : DbContext { }

在应用程序的第一版本。连接字符串类似

<add name="CarContext" providerName="System.Data.SqlClient" Integrated Security=true;
connectionString="Data Source=Dragon; Initial Catalog=CarDBv1;"/>

当我运行应用程序时,数据库的第一个版本 - CarDBv1

When I run application, first version of database is created - CarDBv1.

然后我编辑我的CarContext类,例如添加新表,更改任何属性等,还更改应用程序版本,更改连接字符串

Then I edit my CarContext class, for example, add new table, change any property etc., also change version of application, change connection string

初始目录= CarDBv1; 初始目录= CarDBv2; 在这种情况下,我有2个数据库: CarDBv1 CarDBv2 。但是,CarContext类在应用程序中是相同的。

Initial Catalog=CarDBv1; to Initial Catalog=CarDBv2; and run project. In this case I have 2 database: CarDBv1 and CarDBv2. But, CarContext class is same in applications.

现在,我需要从任何控制台应用程序连接数据库及其上下文(CarContext),并使用它们的表进行转换,读取等等。

Now, I need to connect both database and their context(CarContext) from any console application and use their tables for converting, reading etc.

我在这里找到了类似的答案: http:// stackoverflow。 com / a / 16860878/1534785

I found a similar answer here : http://stackoverflow.com/a/16860878/1534785

但在我的应用程序上下文名称是相同的。

But in my applications context name is same.

如何通过数据库连接字符串为应用程序中的每个CarContext创建2个实例?

How can I create 2 instances for every CarContext in applications by their database connection string?

推荐答案

可以使用重载的构造函数到DbContext允许上下文指向和未声明在app.config中的任意数据库。
查看具有dbConnection的构造函数。

You can use an overloaded constructor to DbContext to allow contexts to point at and arbitrary database which is NOT declared in app.config. See the constructor with dbConnection.

public  class MyDbContext : DbContext, IContextOptions  {
    //ctors
    protected BosBaseDbContext(string connectionName)
        : base(connectionName) {          }

    protected BosBaseDbContext(DbConnection dbConnection, bool contextOwnsConnection)
        : base(dbConnection, contextOwnsConnection) {       }

}

使用

usage

//datasource could be localhost, DBName the catalog name 
new MyDbContext((GetSqlConn4DbName(dataSource,dbName )),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;
    }

这篇关于如何通过连接字符串创建多个数据库环境Intances?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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