gin93r
gin93r

Reputation: 1593

How can I set the Code First connection string via SetParameters with Entity Framework

I have a project that has multiple environments and each environment uses its own database. I've recently switched the database over to EF to make updating it easier. The only catch, I can't seem to get the connection string for EF to transform.

Currently, my process is as follows:

The transforms on the regular connection strings work fine.

According to this documentation, the Web.config file will get an additional connection string added to it. In my case, it's Main_DatabasePublish.

I cannot seem to get that to transform. If I add a default connection to the publish profile, it will get set to that string, but unfortunately it still doesn't get transformed to use the proper database.

I'd like to add that I'm not using EF Core. It seems that that would have been easier with the command line.

Any thoughts?

Update:

Thanks to @SteveGreene, I was able to get this working. Turns out what I needed was to add a few lines to my Application_Start method to call the update. I'm not sure if this is the best way, but it does work.

using System.Data.Entity;
using System.Data.Entity.Migrations;

Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDBContext, MyConfiguration>());
var dbMigrator = new DbMigrator(new MyConfiguration());
dbMigrator.Update();

Upvotes: 1

Views: 55

Answers (1)

gin93r
gin93r

Reputation: 1593

What I ended up doing was adding the following to Global.asax::Application_Start

using System.Data.Entity;
using System.Data.Entity.Migrations;

System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDBContext, Configuration>());
var dbMigrator = new DbMigrator(new Configuration());
var migrations = dbMigrator.GetPendingMigrations();
if (migrations.Any())
{
    dbMigrator.Update();
}

Upvotes: 1

Related Questions