Tip 32 – How to create a database from SSDL – EF 4 only

We recently released a CTP that extends EF 4 Beta 1 which included Code Only.

You can read more about Code Only here, here and here.

If you look at the walkthroughs for Code Only you will see code that looks something like this:

// Create a builder and configure it
var builder = new ContextBuilder<MyContext>();

// Create a context
var mycontext = builder.Create(sqlConnection);

// Prepare the Context
if (!myContext.DatabaseExists())
myContext.CreateDatabase();

CreateDatabase(), DropDatabase(), DatabaseExists() and CreateDatabaseScripts() are all extension methods that ship in the Code Only assembly.

And here’s the neat thing: These extension methods are orthogonal to the rest of Code Only.

You can use these extension methods with any ObjectContext, regardless of whether Code-Only was used to create it.

So you can call these methods on *any* ObjectContext.

Imagine this scenario: Someone else on your team has checked-in an EDMX as part of the project, but when you check out you find their are no database scripts. You could now use Code-Only to create a local database.

These methods look at the database model described in ObjectContext.MetadataWorkspace, and for example produce and execute DDL.

Cool huh?

Now as always this tip comes with some caveats*:

  1. At the moment this only works with EF 4 Beta1. We will ship new versions of Code Only to work with later versions of EF 4 as and when they drop.
  2. CreateDatabase() doesn’t know how to handle everything in the storage model. So for example if your EDMX references database Views or Stored Procedures, Code Only won’t know how to fabricate the database equivalents.
  3. At the moment this only works with SQL Server. We have plans to add a provider model to Code-Only, but that is not there yet.

Despite these limitations, there are doubtless situations where CreateDatabase() and its chums will be useful.

So enjoy!

*It wouldn’t be a tip without caveats :)