11/05/2012

I find it very frustrating that I cannot use the entity model designer to generate code-first DbContext & entities that retains all the aspects of code-first including database initialization.

Here are a set of instructions that can easily help you to achieve true code-first using the EDM designer, and allowing initialization of database (database initialization is not supported in model-first, it only allows generation of database scripts that has to be generated on the server).

This is very useful in small projects where you don’t want to mess with the database, and you rather it being generated automatically.

In my example I chose to use SQL Compact Edition, but you can use SQL Express or other as well.

From the left menu select “Online Templates” then under category “Database” choose EF 4.x DbContext Generator for C# (or different lang.)

Two new template files (*.tt) were generated to the project, open the Context.Context.tt file (the first ‘Context’ should be your model name)

Search for the constructor template, it calls the base constructor:: base(“name=<#=container.Name#>“)Remove the name= from it so it remains : base(“<#=container.Name#>“)

Erease or comment the OnModelCreating method

Add the following lines to your bootstrapper or App_Startup or any point where the application initializes:AppDomain.CurrentDomain.SetData(“DataDirectory”, Environment.CurrentDirectory); Database.DefaultConnectionFactory = newSqlCeConnectionFactory(“System.Data.SqlServerCe.4.0”); Database.SetInitializer(newDropCreateDatabaseIfModelChanges<ContextContainer>());

If it’s not a web application you’re dealing with, you will need to set the DataDirectory variable of the generated connection string, see the first line above.

The second line sets the default connection factory which is the pipe Entity-Framework uses to generate a connection string (and hence a database), you can use either SqlCeConnectionFactory like in the above example, or SqlConnectionFactory and you can even create your own connection factory by implementing IDbConnectionFactory.

You can change the third line by setting the DatabaseInitializer to your own by deriving from the class above (you can use any class that implement IDatabaseInitializer), and override the Seed method, which allows you setting initial database values like deafult username/password etc.

Here is the sample project’s execution, it will automatically generate an sdf database file that will be filled with data with no hassle of servers and all that. In fact you don’t even care what the database schema looks like.