Reputation: 117
I'm trying to find a way to change the database name in my web.config
and my context. No other info in my connection string changes but the database name.
public APIContext(string dbname = "MyFirstDB") : base("OriginalContext")
{
this.Database.Connection.ConnectionString = this.Database.Connection.ConnectionString.Replace("MyFirstDB", dbname);
}
The only way I can find to achieve this is to replace the name, but I can see few problems in the future, for example if I need to go back or need to point to another database. Using mysql.
Any help will be appreciated.
** EDIT **
[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
public class APIContext : DbContext
{
public APIContext() : base("MyContext")
{
}
public void setDatabaseName(string name)
{
var currentdatabase = this.Database.Connection.Database;
this.Database.Connection.ConnectionString = this.Database.Connection.ConnectionString.Replace(currentdatabase, name);
}
Would this work if I were to call the "setDatabaseName(string name)" method before I call my context class?
I'm just confused on where I should be replacing the database name and how to do it.
Upvotes: 2
Views: 7912
Reputation: 3169
Ok, if you want to use more than one connstring you can do this
public class MyModel : DbContext
{
public MyModel ()
: base(ApplicationParameters.ConnectionStringName)
{
}
public MyModel (string connectionStringName)
: base(connectionStringName)
{
}
}
Then in your web.config you can set a list of connstrings and in your code you can call any of them with the second constructor.
Upvotes: 1
Reputation: 3169
Have you tried this?
public partial class MyModel : DbContext
{
public MyModel()
: base("name=MyModelDataContext") // <-- ConnString Name
{
}
}
And your connstring looks like this
<add name="MyModelDataContext" connectionString="data source=... initial catalog=YOURDB
This way you can change your db name any time.
this is actually how the code first from database wizard generates it
Upvotes: 4