问题描述
在C#中,MVC代码第一个应用程序我有
In C#, MVC code first application I have
public class CarContext : DbContext { }
class 。连接字符串就像
class in first version of application. And connection string is like
<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.
我在这里找到了类似的答案:
I found a similar answer here: https://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) { }
}
使用
//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;
}
这篇关于如何通过连接字符串创建多个db上下文实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!