Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automate EF-Migrations "Update-Database -Script"

Tags:

I'm using EF migrations to track changes to our EF code-first DB model. Now I need to generate one SQL-Script for each migration, so that I can pass that set of scripts to the DBA.

I was able to generate SQL scripts with Update-Database -Script ...

However, I'd like to automate this. I hoped that the -Script switch would accept a parameter that specifies where to write the SQL to, but this is not the case. Also, output redirection does not work, because the SQL script is not written to STDOUT, but to a temporary file. I see no way of getting hold of that temp file from a script.

Any ideas how to automate the Migrations -> SQL Script generation? Maybe there is some magic powershell trickery that I'm not aware of?

EDIT: By the way, using migrate.exe or any other "migration-aware" approach is not an option, delivering SQL scripts is a must.

like image 717
theDmi Avatar asked Jan 14 '13 19:01

theDmi


People also ask

How do I update my database in migration?

After creating a migration file using the add-migration command, you have to update the database. Execute the Update-Database command to create or modify a database schema. Use the –verbose option to view the SQL statements being applied to the target database.


1 Answers

Finally I found a solution. What I wasn't aware of is that it is possible to generate SQL scripts from C# code as follows:

using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure;  var migrator = new DbMigrator(new Configuration()); var scriptor = new MigratorScriptingDecorator(migrator); var sql = scriptor.ScriptUpdate("Name-Of-Source-Migration", "Name-Of-Target-Migration"); 

Together with migrator.GetLocalMigrations() you have full control over the granularity of the generated scripts.

like image 107
theDmi Avatar answered Sep 28 '22 11:09

theDmi