Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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=************";
        }
    }
share|improve this question
    
Have a look at config transforms: msdn.microsoft.com/en-us/library/dd465326(v=vs.110).aspx –  Oliver Mar 13 at 17:04

1 Answer 1

up vote 1 down vote accepted

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);
}
share|improve this answer
    
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. –  wotney Mar 13 at 22:48

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.