John
John

Reputation: 7049

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

Upvotes: 4

Views: 6702

Answers (4)

Maxime
Maxime

Reputation: 8969

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);

Upvotes: 3

memoryz
memoryz

Reputation: 494

An approach you can consider is to use ef migrations to generate the script, then use MSBuild post build task to copy the script over to the database project at build time.

Upvotes: 1

John
John

Reputation: 7049

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.

Upvotes: 4

Ilya Schukin
Ilya Schukin

Reputation: 303

You can also generate custom queries using the `ObjectQuery class. Here's an example:

var query = from emp in context.Employees
            select emp;

var sqlScript = ((ObjectQuery)query).ToTraceString();

Upvotes: 1

Related Questions