问题描述
我正在使用EF迁移来跟踪对我们的EF代码优先数据库模型的更改。现在,我需要为每次迁移生成一个SQL脚本,以便将那组脚本传递给DBA。
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.
我能够使用更新数据库-Script ...
但是,我想使它自动化。我希望-Script开关将接受一个参数,该参数指定将SQL写入到的位置,但事实并非如此。另外,输出重定向也不起作用,因为SQL脚本不是写入STDOUT,而是写入临时文件。我看不到从脚本中获取该临时文件的方法。
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.
任何想法如何使迁移-> SQL脚本生成自动化?也许有一些我不知道的神奇的Powershell骗术?
Any ideas how to automate the Migrations -> SQL Script generation? Maybe there is some magic powershell trickery that I'm not aware of?
编辑:顺便说一句,使用migrate.exe或任何其他可识别迁移的方法是
By the way, using migrate.exe or any other "migration-aware" approach is not an option, delivering SQL scripts is a must.
推荐答案
最后我找到了解决方案。我不知道的是可以从C#代码生成SQL脚本,如下所示:
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");
与 migrator.GetLocalMigrations()
一起使用完全控制所生成脚本的粒度。
Together with migrator.GetLocalMigrations()
you have full control over the granularity of the generated scripts.
这篇关于使EF迁移“更新数据库-脚本”自动化。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!