I am using EF migrations to dynamically create a database model at run-time. This can happen many times, sometimes modifying existing tables and sometimes not. As every time i do a migration I don't want to create a massive context containing all the DbSets on the whole database I just want to include the tables I'm currently modifying.
I am doing the migration in the following way
Type contextType = null; //This will be my dbcontext
DbMigrationsConfiguration migratorConfig = new DbMigrationsConfiguration();
migratorConfig.ContextType = contextType;
migratorConfig.TargetDatabase = new DbConnectionInfo("ConnectionString", "System.Data.SqlClient");
migratorConfig.AutomaticMigrationsEnabled = true;
migratorConfig.AutomaticMigrationDataLossAllowed = false;
migratorConfig.ContextKey = "key";
migratorConfig.MigrationsAssembly = contextType.Assembly;
DbMigrator dbMigrator = new DbMigrator(migratorConfig);
dbMigrator.Update();
Is there any way I can configure EF to not drop the tables that are not included on the context but were present on previous migrations? Using a different ContextKey
each time is not an option because EF will complain that a certain object already exists.
Thanks in advance.
You can employ
migrator.GetDatabaseMigrations();
which returns the correct list of migrations already applied to the database. And use the following due to get the pending migrations:And you may wanna see the scripts by this:
Then try to see/compare them to meet your purpose. You may wanna customize Migrations History Table to meat this :)
Note: Renaming the
ContextKey
is useful to deal with managing multiple models per physical database instance. This is an ability in EF6 Migrations known as Multiple Contexts per Database. According to MSDN theContextKey
:One way to do it is to use manual migrations, but this would be a bit difficult to achieve, however if you have a larger database and have lower number of modifications, this should work.
use something like,
Please find more information here