0

I've built my project and named the db connection "VMaxEntities"

The connection string exists in web.config.

I have another connection string "Development_VMaxEntities"

Whenever I call the db, I use the code using (VMaxEntities db = new VMaxEntities())

This calls:

public partial class VMaxEntities : DbContext { public VMaxEntities() : base("name=VMaxEntities") { }

What I want to do is connect to a development database instead of the live one, IF the current URI contains localhost.

So - thanks to cgotberg's answer below, here's what I used to get it working: (note, I add the password here instead of in web.config)

 public VMaxEntities()
        : base("name=Secure_VMaxEntities")
    {
        if (System.Web.HttpContext.Current.Request.Url.Host == "localhost")
        {
            var connectionString = this.Database.Connection.ConnectionString + ";password=***********";
            this.Database.Connection.ConnectionString = connectionString.Replace("catalog=VMax", "catalog=DEV_VMax");
        }
        else
        {
            this.Database.Connection.ConnectionString += ";password=************";
        }
    }
1

1 Answer 1

2

I've done something like this in the past

using(var db = new VMaxEntities())
{
   var connectionString = context.Database.Connection.ConnectionString;
   var datasource = context.Database.Connection.DataSource;
   var databaseServer = "yourDevDatabaseServerName"        

   db.Database.Connection.ConnectionString = connectionString.Replace(datasource, databaseServer);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that helped. I marked as answer, but it's not the dataSource part of the connection string I wanted to change, just the "initial catalog" name eg. the database name. Both DBs live on the same server.

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.