Mazhar Hayat
Mazhar Hayat

Reputation: 73

Switch database during setup with Entity Framework Code-First approach

I am working on a asp.net mvc project. I want to know how can I change/switch database with new database during the setup of application (by client itself ) without running the migrations manually on the new database.

I want to change the database name in the connection string and that's it. My project should configure and works well with the new database.

Please suggest a solution.

Upvotes: 1

Views: 601

Answers (2)

jitendra singh
jitendra singh

Reputation: 155

As mentioned by Iraj, there is a Database Initializer that you can use to set migration with the changed database during the startup as:

Database.SetInitializer<ObjectContext>(
    new MigrateDatabaseToLatestVersion<ObjectContext, Configuration>());

Another approach:

var Configuration = new DbContextConfiguration();
Configuration.TargetDatabase = new DbConnectionInfo(
    database.ConnectionString, database.ProviderName);

var MyMigrator = new DbMigrator(configuration);
MyMigrator.Update();
MyMigrator.GetPendingMigrations(); ' Optional

You can also create a setup page that can take database name (or complete connection string) as input from your clients and you can use that to run migration via code when they run the application. Voila!

Reference - http://romiller.com/2012/02/09/running-scripting-migrations-from-code/

[Update] A small trick, you can use Entity Framework migration feature for your development and once you are done with finalizing the entities and everything then you can simply delete migration files and remove its hook from your application and share it with the client/users. Then entity framework by default will create new database or will update any existing database with your project entities. You can check the same with default asp.net web api template. On creating new project, if you select asp.net identity for authentication it includes few entities which gets created automatically on running the application first time.

Upvotes: 1

Iraj
Iraj

Reputation: 1522

you can set "MigrateDatabaseToLatestVersion" in Configuration file :

internal sealed class Configuration : System.Data.Entity.MigrateDatabaseToLatestVersion<DbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
        //..................
    }

    protected override void Seed(DbContext context)
    {
        ///....
    }
}

Update:

you can set Database.SetInitializer in global.asax file:

    protected void Application_Start()
    {
      ....
      Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDbContext, Configuration>());
    }

Upvotes: 1

Related Questions