Entity Framework Code-First: migrate a database known only at runtime

I am trying to migrate a database that is known only at run time, which means that I cannot use the Package Manager console to update the database. In addition, this is not only one, but also many databases, but for all this is the same scheme :)

I use Ninject to generate and enter a connection string in an object DbContext. The context constructor looks like this:

public class MyEntities : DbContext
{
    public MyEntities(string database) : base(database) { }
    /* Properties code omitted. */
}

The following is a method to create an instance of a context:

public MyEntities GetDatabase(string databaseName, string connectionString)
{
    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
    builder.InitialCatalog = databaseName;

    MyEntities context = this._kernel.Get<MyEntities>(new ConstructorArgument(
        "database", builder.ConnectionString));

    Database.SetInitializer<MyEntities>(
        new MigrateDatabaseToLatestVersion<MyEntities, MyEntitiesMigrationConfiguration>("MyEntities"));

    return context;
}

When the context is retrieved, the method creates a connection string and passes it as a parameter to the constructor MyEntities. I also specify in the method the type of migration that I want (in this case MigrateDatabaseToLatestVersion).

Following is the migration code:

public partial class MyAccountInMonth : DbMigration
{
    public override void Up()
    {
        AlterColumn("AccountsInMonths", "MovementDebtMonth", c => c.Long(nullable: false));
        AlterColumn("AccountsInMonths", "MovementCreditMonth", c => c.Long(nullable: false));
        AlterColumn("AccountsInMonths", "BalanceMonth", c => c.Long(nullable: false));
        AlterColumn("AccountsInMonths", "MovementDebtAccumulated", c => c.Long(nullable: false));
        AlterColumn("AccountsInMonths", "MovementCreditAccumulated", c => c.Long(nullable: false));
        AlterColumn("AccountsInMonths", "BalanceAccumulated", c => c.Long(nullable: false));
    }

    public override void Down() { /* Code omitted */ }
}

:

Cannot find the object "AccountsInMonths" because it does not exist or you do not have permissions.

, AccountsInMonths int long.

, . , , . - - . , ? !

PS: , .

+3
3

Visual Studio , migrate.exe, Nortel EntityFramework. .

+2

. :

1) Configuration :

public sealed class Configuration : DbMigrationsConfiguration<YourContextClassHere>

2) Seed()

2) - , db:

Configuration configuration = new Configuration();
configuration.ContextType = typeof(YourContextClassHere);
var migrator = new DbMigrator(configuration);

// This will update the schema of the DB
migrator.Update();
// This will run Seed() method
configuration.Seed(new YourContextClassHere());
+2

Update-Database. - ($ConnectionString $ConnectionProviderName) config ($ConnectionStringName).

DbMigrator, ( , migrate.exe).

+1
source

All Articles