Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First Migrations: get sql scripts programmatically

I am implementing Entity Framework (v5) Code-Based Migrations for my project.

The db admins from our clients are sometimes a little bit paranoid and want to execute the sql scripts by hand.

Since we have got already many versions and we support SqlServer and Oracle parallel, we don't want to administer several update scripts from all possible versions x.x.x.x to y.y.y.y. Is it not possible to get programmatically the sql script in the same way as I call it in the Package Manager Console

Update-Database -Script

So the client would get via a simple console application depending his db system and current version the correct sql script as output.

like image 972
StefanG Avatar asked Nov 25 '13 14:11

StefanG


People also ask

Can we run SQL script using code First migrations?

Code First Migrations will run the migration pipeline but instead of actually applying the changes it will write them out to a . sql file for you. Once the script is generated, it is opened for you in Visual Studio, ready for you to view or save.

Which command generate SQL script from migrations?

With From and To The following generates a SQL script from the specified from migration to the specified to migration. You can use a from that is newer than the to in order to generate a rollback script.

How do I code my first migration to an existing database?

Run the Add-Migration InitialCreate command in Package Manager Console. This creates a migration to create the existing schema. Comment out all code in the Up method of the newly created migration. This will allow us to 'apply' the migration to the local database without trying to recreate all the tables etc.


1 Answers

  var configuration = new Configuration();
  var migrator = new DbMigrator(configuration);

  var scriptor = new MigratorScriptingDecorator(migrator);
  var script = scriptor.ScriptUpdate(sourceMigration: null, targetMigration: null);
  Console.WriteLine(script);

  migrator.Update();

  var pending = migrator.GetPendingMigrations();

more info: http://weblogs.asp.net/fredriknormen/archive/2012/02/15/using-entity-framework-4-3-database-migration-for-any-project.aspx


basically you need

DbMigrator db = new DbMigrator(HERE CONNECTION STRING);
db.Update(HERE TARGET VERSION);
like image 198
Bassam Alugili Avatar answered Nov 14 '22 23:11

Bassam Alugili