Search code examples
c#entity-frameworkdatabase-connectionweb.config-transform

How to change db connection programmatically c# Entity Framework


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=************";
        }
    }

Solution

  • 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);
    }