I'm using entity framework with code-first (primarily because with RIA Services, you need to have some form of the code classes anyway for additional attributes).
I want to get a database generation script to easily update the visual studio database project. I don't want to use ef migrations, I prefer the database projects.
I can use something like
string sqlscript = (context as IObjectContextAdapter).ObjectContext.CreateDatabaseScript();
at runtime, but I want to have a convenient method to get the script without running the project in some way, and without using migrations.
Does anybody have any ideas?
I'm using ef4.1 and ef5 in different projects.
[EDIT: One way of answering this question would be a way to call above line from the package manager console.]
One way is using the Entity Framework Power Tools. They add a context menu entry for the file containing the DbContext class which generates a DDL file for the database.
Another way is using LinqPad. After opening the dll in LinqPad, one can execute the code snippet given in the question in a query:
(this as IObjectContextAdapter).ObjectContext.CreateDatabaseScript()
Both ways are slightly inconvenient though as they require third-party tools.
I have enabled migrations but I always do get the script at runtime without using the Package Manager Console to update the database as I have dynamic entities that can only be discovered at runtime depending on what references are included in the project.
The code to get the script looks like this:
var config = new DbMigrationsConfiguration<MyContext> { AutomaticMigrationsEnabled = true };
var migrator = new DbMigrator(config);
var scriptor = new MigratorScriptingDecorator(migrator);
string script = scriptor.ScriptUpdate(sourceMigration: null, targetMigration: null);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With