问题
In C#, MVC code first application I have
public class CarContext : DbContext { }
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;"/>
When I run application, first version of database is created - CarDBv1.
Then I edit my CarContext class, for example, add new table, change any property etc., also change version of application, change connection string
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.
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.
How can I create 2 instances for every CarContext in applications by their database connection string?
回答1:
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;
}
来源:https://stackoverflow.com/questions/17739666/how-create-multiple-db-context-instances-by-connecting-strings