0

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 Answer 1

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;
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.