Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a database script from entity framework code-first model

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.]

like image 834
John Avatar asked Jan 15 '23 01:01

John


2 Answers

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.

like image 149
John Avatar answered Jan 19 '23 11:01

John


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);
like image 40
Maxime Avatar answered Jan 19 '23 10:01

Maxime